package com.example.lj.uav.widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.adapter.SpinnerDropDownAdapter;
import com.example.lj.uav.bean.BatteryItem;
import com.example.lj.uav.utils.AnimUtils;
import com.example.lj.uav.utils.OnUIUtils;
import com.example.lj.uav.view.ControllerSettingActivity;
import com.example.lj.uav.view.ManualFlightActivity;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import dji.common.airlink.ChannelInterference;
import dji.common.airlink.ChannelSelectionMode;
import dji.common.airlink.LightbridgeFrequencyBand;
import dji.common.airlink.PhysicalSource;
import dji.common.airlink.WifiDataRate;
import dji.common.battery.BatteryState;
import dji.common.error.DJIError;
import dji.common.flightcontroller.CompassState;
import dji.common.flightcontroller.ConnectionFailSafeBehavior;
import dji.common.flightcontroller.FlightControllerState;
import dji.common.flightcontroller.imu.IMUState;
import dji.common.flightcontroller.imu.SensorState;
import dji.common.model.LocationCoordinate2D;
import dji.common.remotecontroller.AircraftMappingStyle;
import dji.common.remotecontroller.Credentials;
import dji.common.remotecontroller.PIPPosition;
import dji.common.remotecontroller.ProfessionalRC;
import dji.common.remotecontroller.RCMode;
import dji.common.remotecontroller.SecondaryVideoDisplayMode;
import dji.common.remotecontroller.SecondaryVideoFormat;
import dji.common.remotecontroller.SecondaryVideoOutputPort;
import dji.common.util.CommonCallbacks;
import dji.sdk.airlink.AirLink;
import dji.sdk.airlink.LightbridgeLink;
import dji.sdk.airlink.OcuSyncLink;
import dji.sdk.airlink.WiFiLink;
import dji.sdk.base.BaseProduct;
import dji.sdk.battery.Battery;
import dji.sdk.camera.Camera;
import dji.sdk.flightcontroller.Compass;
import dji.sdk.flightcontroller.FlightAssistant;
import dji.sdk.flightcontroller.FlightController;
import dji.sdk.flightcontroller.LandingGear;
import dji.sdk.gimbal.Gimbal;
import dji.sdk.products.Aircraft;
import dji.sdk.remotecontroller.RemoteController;
import dji.sdk.sdkmanager.DJISDKManager;
import dji.sdk.sdkmanager.LiveStreamManager;

import static com.example.lj.uav.MyApplication.mPref;

public class FlightSettingLayout extends FrameLayout implements View.OnClickListener,
        CompoundButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener,
        AdapterView.OnItemSelectedListener, RadioGroup.OnCheckedChangeListener,
        DialogInterface.OnDismissListener, IMUState.Callback, CompassState.Callback {

    private Context context;
    private ManualFlightActivity mActivity;
    private View view;
    private LinearLayout[] layouts;
    private LinearLayout firstLayout;
    private LinearLayout secondLayout;
    private LinearLayout ll_imu;
    private LinearLayout ll_compass;
    private LinearLayout ll_professional_custom_controls;
    private LinearLayout ll_channel;
    private FrameLayout fl_title_back;
    private FrameLayout fl_imu_index_1;
    private FrameLayout fl_imu_index_2;
    private FrameLayout fl_compass_index_1;
    private FrameLayout fl_compass_index_2;
    private int lastPage;
    private int initProgress;

    private Spinner sp_lose_cnn_action;
    private Spinner sp_work_channel;
    private Spinner sp_out_put_mode;
    private Spinner sp_out_put_formate;
    private Spinner sp_pip;
    private Spinner sp_tap_zoom;
    private Spinner sp_master_slave;
    private Spinner sp_limit;
    private EditText et_air_bg;
    private Spinner sp_unit;
    private Spinner sp_cloud;
    private SpinnerDropDownAdapter actionAdapter;
    private SpinnerDropDownAdapter portAdapter;
    private SpinnerDropDownAdapter mapAdapter;
    private SpinnerDropDownAdapter cameraAdapter;
    private SpinnerDropDownAdapter displayModeAdapter;
    private SpinnerDropDownAdapter formateAdapter;
    private SpinnerDropDownAdapter pipAdapter;
    private SpinnerDropDownAdapter masterSlaveAdapter;
    private String[] lose_cnn_actions = new String[]{"悬停", "下降", "返航"};
    private String[] app_output_ports = new String[]{"HDMI", "SDI"};
    private String[] work_channels;
    private String[] map_types = new String[]{"自动", "高德地图", "MapBox"};
    private String[] camera_settings = new String[]{"打开/关闭机头指示灯", "中央重点侧光", "AE锁定/解锁", "相机高级设置",
            "回中/朝下", "FPV模式/跟随模式", "地图/FPV切换", "电池页面", "回放", "中心点对焦", "未定义"};
    private String[] output_pip = new String[]{"左上", "右上", "左下", "右下"};//画中画
    private String[] output_mode = new String[]{"只有1视频", "只有2视频", "1视频为主", "2视频为主"};
    private String[] output_formate = new String[]{"1080I 60FPS", "1080I 50FPS", "1080P 60FPS", "1080P 50FPS", "1080P 30FPS",
            "1080P 25FPS", "1080P 24FPS", "720P 60FPS", "720P 50FPS", "720P 30FPS", "720P 25FPS", "720P 24FPS"};
    private String[] tap_zoom_state = new String[]{"1x", "2x", "3x", "4x", "5x"};
    private String[] master_slave_state = new String[]{"主控", "辅控", "正常"};
    private int main_camera_setting = 6;//默认左相机
    private int assistant_camera_setting = 7;//默认右相机
    private String[] alarm_limits = new String[]{"100ppm*m", "200ppm*m", "300ppm*m","自定义"};
    private String[] air_bgs = new String[]{"0ppm*m"};
    private String[] unit_settings = new String[]{"ppm*m"};
    private String[] cloud_datas = new String[]{"Auto"};
    private String selected_unit = "";
    private int currentMainCameraIndex;
    private int currentAssistantCameraIndex;

    private TextView tv_title;
    private TextView tv_bandwidth_hdmi;
    private TextView tv_bandwidth_av;
    private TextView tv_serious_lowbattery_warning;
    private TextView tv_lowbattery_warning;
    private TextView tv_acc_state;
    private TextView tv_gyro_state;
    private TextView tv_remote_pairing;
    private TextView tv_gimbal_no;
    private TextView pct_top;
    private TextView pct_left;
    private TextView pct_bottom;
    private TextView pct_right;
    private CheckBox cb_flightmode;
    private CheckBox cb_maxradius;
    private CheckBox cb_tripodmode;
    private CheckBox cb_gear;
    private CheckBox cb_collision_avoidance;
    private CheckBox cb_landing_protection;
    private CheckBox cb_rth_avoidance;
    private CheckBox cb_ext_port;
    private CheckBox cb_smart_rth;
    private CheckBox cb_gimbal_limit;
    private CheckBox cb_radar;
    private CheckBox cb_track;
    private CheckBox cb_beeping;
    private CheckBox cb_osd;
    private EditText et_gohomeheight;
    private EditText et_maxheight;
    private EditText et_devicename;
    private RadioGroup rg_channel_choice;
    private RadioGroup rg_sensor;
    private RadioGroup rg_gesture;
    private RadioButton rb_automatic;
    private RadioButton rb_manual;
    private RadioButton rb_imu;
    private RadioButton rb_compass;
    private RadioButton rb_jap;
    private RadioButton rb_usa;
    private RadioButton rb_chn;
    private SeekBar sb_bandwidth;
    private SeekBar sb_serious_lowbattery_warning;
    private SeekBar sb_lowbattery_warning;
    private SeekBar sb_top;
    private SeekBar sb_left;
    private SeekBar sb_bottom;
    private SeekBar sb_right;
    private LinearLayout ll_custom;
    private EditText et_custom;
    private int savedLoseCnnPosition, savedFrequencePosition;
    private int[] fullBatteries;
    private RadioButton lastRB, curRB;
    private FrameLayout fl7;

    private SecondaryVideoOutputPort selectedPort;
    private SecondaryVideoFormat selectedFormate;
    private StringBuilder gimbalBuilder;
    private RecyclerView rv_battery_info;
    private ListView lv_battery_info;
    //    private BatteryInfoAdapter batteryInfoAdapter;
    private List<BatteryItem> batteryItems;
    private ChannelLayout cl_channelLayout;
    private List<Camera> cameras;
    private int[] remainBatteris;

    public FlightSettingLayout(@NonNull Context context) {
        super(context);
        this.context = context;
        mActivity = (ManualFlightActivity) context;
        initView(context);
        initBySDK();
    }

    public FlightSettingLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        mActivity = (ManualFlightActivity) context;
        initView(context);
        initBySDK();
    }

    public FlightSettingLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        mActivity = (ManualFlightActivity) context;
        initView(context);
        initBySDK();
    }

    private void initView(final Context context) {
        view = LayoutInflater.from(context).inflate(R.layout.layout_flightsetting, this);
        view.findViewById(R.id.flightsetting_fl_0).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_fl_1).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_fl_2).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_fl_3).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_fl_4).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_fl_5).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_fl_6).setOnClickListener(this);
        view.findViewById(R.id.btn_change_sourse_input).setOnClickListener(this);
        fl7 = view.findViewById(R.id.flightsetting_fl_7);
        fl7.setOnClickListener(this);
        BaseProduct product = MyApplication.getProductInstance();
        if (product != null) {
            fl7.setVisibility(View.VISIBLE);
        }
        layouts = new LinearLayout[8];
        layouts[0] = view.findViewById(R.id.flightsetting_ll_flightcontrol);
        layouts[1] = view.findViewById(R.id.flightsetting_ll_perception);
        layouts[2] = view.findViewById(R.id.flightsetting_ll_remote_control);
        layouts[3] = view.findViewById(R.id.flightsetting_ll_send_pictures);
        layouts[4] = view.findViewById(R.id.flightsetting_ll_smart_battery);
        layouts[5] = view.findViewById(R.id.flightsetting_ll_ptz);
        layouts[6] = view.findViewById(R.id.flightsetting_ll_common);
        layouts[7] = view.findViewById(R.id.flightsetting_ll_watcher);
        firstLayout = layouts[0];
        lastPage = 0;

        tv_title = view.findViewById(R.id.flightsetting_tv_title);
        fl_title_back = view.findViewById(R.id.flightsetting_fl_title_back);
        fl_title_back.setOnClickListener(this);
        view.findViewById(R.id.flightsetting_fl_title_cancel).setOnClickListener(this);
        tv_gimbal_no = view.findViewById(R.id.tv_flightsetting_gimbal_no);
        lv_battery_info = findViewById(R.id.flightsetting_lv_battery_info);

        sp_lose_cnn_action = view.findViewById(R.id.sp_flightsetting_lose_connect_action);
        actionAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank,
                R.id.tv_item_menu_blank_tv, lose_cnn_actions, 1, sp_lose_cnn_action);
        actionAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
        sp_lose_cnn_action.setAdapter(actionAdapter);
        sp_lose_cnn_action.setOnItemSelectedListener(this);

        Spinner sp_camera_c1 = view.findViewById(R.id.sp_flight_setting_camera_setting_c1);
        cameraAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank,
                R.id.tv_item_menu_blank_tv, camera_settings, 1, sp_camera_c1);
        cameraAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
        sp_camera_c1.setAdapter(cameraAdapter);
        sp_camera_c1.setOnItemSelectedListener(this);
        sp_camera_c1.setSelection(3);

        Spinner sp_camera_c2 = view.findViewById(R.id.sp_flight_setting_camera_setting_c2);
        sp_camera_c2.setAdapter(cameraAdapter);
        sp_camera_c2.setOnItemSelectedListener(this);
        sp_camera_c2.setSelection(3);

        Spinner sp_output_port = view.findViewById(R.id.sp_flight_setting_app_output_port);
        portAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank,
                R.id.tv_item_menu_blank_tv, app_output_ports, 1, sp_camera_c2);
        portAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
        sp_output_port.setAdapter(portAdapter);
        sp_output_port.setOnItemSelectedListener(this);

        Spinner sp_map_choose = view.findViewById(R.id.sp_flight_setting_map_choose);
        mapAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank,
                R.id.tv_item_menu_blank_tv, map_types, 1, sp_map_choose);
        mapAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
        sp_map_choose.setAdapter(mapAdapter);
        sp_map_choose.setOnItemSelectedListener(this);

        sp_tap_zoom = view.findViewById(R.id.sp_flight_setting_tap_zoom);
        SpinnerDropDownAdapter tapZoomAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank,
                R.id.tv_item_menu_blank_tv, tap_zoom_state, 1, sp_tap_zoom);
        tapZoomAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
        sp_tap_zoom.setAdapter(tapZoomAdapter);
        sp_tap_zoom.setOnItemSelectedListener(this);
        //图传相机参数设置
        if (product != null) {
            cameras = product.getCameras();
            if (cameras != null && cameras.size() > 0) {
                String[] cameraNames = new String[cameras.size()];
                for (int i = 0; i < cameras.size(); i++) {
                    cameraNames[i] = (cameras.get(i).getDisplayName());
                }
                Spinner sp_main_camera = view.findViewById(R.id.sp_flight_setting_main_camera);
                SpinnerDropDownAdapter mainCameraAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv, cameraNames, 1, sp_main_camera);
                sp_main_camera.setAdapter(mainCameraAdapter);
                sp_main_camera.setOnItemSelectedListener(this);

                String[] cameraNames1 = new String[cameraNames.length + 1];
                System.arraycopy(cameraNames, 0, cameraNames1, 0, cameraNames.length);
                cameraNames1[cameraNames1.length - 1] = "FVP相机";
                Spinner sp_assistant_camera = view.findViewById(R.id.sp_flight_setting_assistant_camera);
                SpinnerDropDownAdapter assistantCameraAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv, cameraNames1, 1, sp_assistant_camera);
                sp_assistant_camera.setAdapter(assistantCameraAdapter);
                sp_assistant_camera.setOnItemSelectedListener(this);
                sp_assistant_camera.setSelection(1);

            }
        }
        ll_custom = view.findViewById(R.id.ll_flight_setting_custom_limit);
        et_custom = view.findViewById(R.id.et_flight_setting_custom_limit);
        sp_limit = view.findViewById(R.id.sp_flightsetting_alarm_limit);
        SpinnerDropDownAdapter limitAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv, alarm_limits, 1, sp_limit);
        sp_limit.setAdapter(limitAdapter);

        int limit = mPref.getInt("alarm_limit", 0);
        boolean isCustomLimit = mPref.getBoolean("is_alarm_limit_custom",false);
        if (isCustomLimit){
            sp_limit.setSelection(3);
            et_custom.setText(limit);
        }else{
            if (limit == 100) {
                sp_limit.setSelection(0);
            } else if (limit == 200) {
                sp_limit.setSelection(1);
            } else if (limit == 300) {
                sp_limit.setSelection(2);
            } else if (limit == 0) {
                sp_limit.setSelection(0);
            }
        }
        sp_limit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                boolean isCustom = false;
                switch (position) {
                    case 0:
                        mPref.edit().putInt("alarm_limit", 100).apply();
                        isCustom = false;
                        ll_custom.setVisibility(View.GONE);
                        break;
                    case 1:
                        mPref.edit().putInt("alarm_limit", 200).apply();
                        isCustom = false;
                        ll_custom.setVisibility(View.GONE);
                        break;
                    case 2:
                        mPref.edit().putInt("alarm_limit", 300).apply();
                        isCustom = false;
                        ll_custom.setVisibility(View.GONE);
                        break;
                    case 3:
                        isCustom = true;
                        mPref.edit().putInt("alarm_limit", 100).apply();
                        ll_custom.setVisibility(View.VISIBLE);
                        break;
                }
                mPref.edit().putBoolean("is_alarm_limit_custom", isCustom).apply();
                if (finishListener != null)
                    finishListener.onFinish();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                if (finishListener != null)
                    finishListener.onFinish();
            }
        });
        et_custom.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String str = et_custom.getText().toString().trim();
                if ("".equals(str)){
                    mPref.edit().putInt("alarm_limit",0).apply();
                }else{
                    mPref.edit().putInt("alarm_limit",Integer.parseInt(str)).apply();
                }
            }
        });

        et_air_bg = view.findViewById(R.id.et_flightsetting_air_bg);
//        SpinnerDropDownAdapter airAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv, air_bgs, 1, et_air_bg);
//        et_air_bg.setAdapter(airAdapter);
//        et_air_bg.setOnItemSelectedListener(this);
        int air_bg = mPref.getInt("air_bg",0);
        et_air_bg.setText(String.valueOf(air_bg));
        et_air_bg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String str = et_air_bg.getText().toString().trim();
                if ("".equals(str)){
                    mPref.edit().putInt("air_bg",0).apply();
                }else{
                    mPref.edit().putInt("air_bg",Integer.parseInt(str)).apply();
                }
            }
        });

        sp_unit = view.findViewById(R.id.sp_flightsetting_measure_unit);
        SpinnerDropDownAdapter unitAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv, unit_settings, 1, sp_unit);
        sp_unit.setAdapter(unitAdapter);
        sp_unit.setOnItemSelectedListener(this);

        sp_cloud = view.findViewById(R.id.sp_flightsetting_cloud_data);
        SpinnerDropDownAdapter cloudAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv, cloud_datas, 1, sp_cloud);
        sp_cloud.setAdapter(cloudAdapter);
        sp_cloud.setOnItemSelectedListener(this);

        //飞行模式是否可变
        cb_flightmode = view.findViewById(R.id.flightsetting_cb_flightmode);
        cb_flightmode.setOnCheckedChangeListener(this);
        //返航高度
        et_gohomeheight = view.findViewById(R.id.flightsetting_et_gohomeheight);
        et_gohomeheight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setGoHomeHeight(Integer.parseInt(s + ""));
                if (finishListener != null)
                    finishListener.onFinish();
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (finishListener != null)
                    finishListener.onFinish();
            }
        });
        //MAX高度
        et_maxheight = view.findViewById(R.id.flightsetting_et_maxheight);
        et_maxheight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setMaxHeight(Integer.parseInt(s + ""));
                if (finishListener != null)
                    finishListener.onFinish();
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (finishListener != null)
                    finishListener.onFinish();
            }
        });
        //MAX距离限制
        cb_maxradius = view.findViewById(R.id.flightsetting_cb_maxradius);
        cb_maxradius.setOnCheckedChangeListener(this);

        //脚架模式
        cb_tripodmode = view.findViewById(R.id.flightsetting_cb_tripodmode);
        cb_tripodmode.setOnCheckedChangeListener(this);

        //脚架
        cb_gear = view.findViewById(R.id.flightsetting_cb_gear);
        cb_gear.setOnCheckedChangeListener(this);

        //视觉避障
        cb_collision_avoidance = view.findViewById(R.id.flightsetting_cb_collision_avoidance);
        cb_collision_avoidance.setOnCheckedChangeListener(this);

        //下视视觉
        cb_landing_protection = view.findViewById(R.id.flightsetting_cb_landing_protection);
        cb_landing_protection.setOnCheckedChangeListener(this);

        //返航障碍物检测
        cb_rth_avoidance = view.findViewById(R.id.flightsetting_cb_rth_avoidance);
        cb_rth_avoidance.setOnCheckedChangeListener(this);

        //信道模式
        rb_automatic = view.findViewById(R.id.flightsetting_rb_automatic);
        rb_manual = view.findViewById(R.id.flightsetting_rb_manual);
        rg_channel_choice = view.findViewById(R.id.flightsetting_rg_channel_choice);
        rg_channel_choice.setOnCheckedChangeListener(this);

        //EXT端口
        cb_ext_port = view.findViewById(R.id.flightsetting_cb_ext_port);
        cb_ext_port.setOnCheckedChangeListener(this);

        //HDMI AV
        tv_bandwidth_hdmi = view.findViewById(R.id.flightsetting_tv_bandwidth_hdmi);
        tv_bandwidth_av = view.findViewById(R.id.flightsetting_tv_bandwidth_av);
        sb_bandwidth = view.findViewById(R.id.flightsetting_sb_bandwidth);
        sb_bandwidth.setOnSeekBarChangeListener(this);
        sb_bandwidth.setProgress(0);
        tv_bandwidth_hdmi.setText(getResources().getString(R.string.flightsetting_bandwidth_hdmi, 0));
        tv_bandwidth_av.setText(getResources().getString(R.string.flightsetting_bandwidth_av, 100));

        //智能返航
        cb_smart_rth = view.findViewById(R.id.flightsetting_cb_smart_rth);
        cb_smart_rth.setOnCheckedChangeListener(this);

        //严重低电量报警
        sb_serious_lowbattery_warning = view.findViewById(R.id.flightsetting_sb_serious_lowbattery_warning);
        tv_serious_lowbattery_warning = view.findViewById(R.id.flightsetting_tv_serious_lowbattery_warning);
        sb_serious_lowbattery_warning.setOnSeekBarChangeListener(this);
        sb_serious_lowbattery_warning.setMax(35);
        sb_serious_lowbattery_warning.setProgress(35);

        //低电量报警
        sb_lowbattery_warning = view.findViewById(R.id.flightsetting_sb_lowbattery_warning);
        tv_lowbattery_warning = view.findViewById(R.id.flightsetting_tv_lowbattery_warning);
        sb_lowbattery_warning.setOnSeekBarChangeListener(this);
        sb_lowbattery_warning.setMax(35);
        sb_lowbattery_warning.setProgress(35);

        //传感器状态
        view.findViewById(R.id.flightsetting_ll_sensor_state).setOnClickListener(this);
        rb_imu = view.findViewById(R.id.flightsetting_rb_imu);
        rb_compass = view.findViewById(R.id.flightsetting_rb_compass);
        rg_sensor = view.findViewById(R.id.flightsetting_rg_sensor);
        rg_sensor.setOnCheckedChangeListener(this);

        //imu
        ll_imu = view.findViewById(R.id.flightsetting_ll_imu);
        fl_imu_index_1 = view.findViewById(R.id.flightsetting_fl_imu_index_1);
        fl_imu_index_2 = view.findViewById(R.id.flightsetting_fl_imu_index_2);
        tv_acc_state = view.findViewById(R.id.flightsetting_tv_acc_state);
        tv_gyro_state = view.findViewById(R.id.flightsetting_tv_gyro_state);
        view.findViewById(R.id.flightsetting_tv_calibration_imu).setOnClickListener(this);

        //compass
        ll_compass = view.findViewById(R.id.flightsetting_ll_compass);
        fl_compass_index_1 = view.findViewById(R.id.flightsetting_fl_compass_index_1);
        fl_compass_index_2 = view.findViewById(R.id.flightsetting_fl_compass_index_2);
        view.findViewById(R.id.flightsetting_tv_calibration_compass).setOnClickListener(this);


        //摇杆模式
        view.findViewById(R.id.flightsetting_ll_rocker_mode).setOnClickListener(this);
        rb_jap = view.findViewById(R.id.flightsetting_rb_jap);
        rb_usa = view.findViewById(R.id.flightsetting_rb_usa);
        rb_chn = view.findViewById(R.id.flightsetting_rb_chn);

        lastRB = rb_usa;
        curRB = rb_usa;
        rg_gesture = view.findViewById(R.id.flightsetting_rg_gesture);
        rg_gesture.setOnCheckedChangeListener(this);

        //遥控器对频
        tv_remote_pairing = view.findViewById(R.id.flightsetting_tv_remote_pairing);
        tv_remote_pairing.setOnClickListener(this);

        //电池详情
        view.findViewById(R.id.flightsetting_ll_battery_info).setOnClickListener(this);
        lv_battery_info = view.findViewById(R.id.flightsetting_lv_battery_info);
        rv_battery_info = view.findViewById(R.id.flightsetting_rv_battery_info);
        rv_battery_info.setLayoutManager(new LinearLayoutManager(context));
        rv_battery_info.setAdapter(new BatteryAdapter());

        //设备名称
        view.findViewById(R.id.flightsetting_ll_devicename).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_tv_save_devicename).setOnClickListener(this);
        et_devicename = view.findViewById(R.id.flightsetting_et_devicename);

        //直播
        view.findViewById(R.id.flightsetting_ll_live_stream).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_ll_2_live_stream).setOnClickListener(this);

        //关于
        view.findViewById(R.id.flightsetting_ll_about).setOnClickListener(this);

        //云台
        cb_gimbal_limit = view.findViewById(R.id.flightsetting_cb_gimbal_limit);
        cb_gimbal_limit.setOnCheckedChangeListener(this);
        view.findViewById(R.id.flightsetting_tv_reset_gimbal).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_tv_gimbal_autocalibration).setOnClickListener(this);

        //返航点
        view.findViewById(R.id.flightsetting_tv_homepoint_craft_location).setOnClickListener(this);
        view.findViewById(R.id.flightsetting_tv_homepoint_home_location).setOnClickListener(this);

        //数据库更新
//        view.findViewById(R.id.flightsetting_tv_update_craft).setOnClickListener(this);
//        view.findViewById(R.id.flightsetting_tv_update_app).setOnClickListener(this);
//        view.findViewById(R.id.flightsetting_tv_update_base).setOnClickListener(this);

        //雷达
        cb_radar = view.findViewById(R.id.flightsetting_cb_radar);
        cb_radar.setOnCheckedChangeListener(this);

        //航迹
        cb_track = view.findViewById(R.id.flightsetting_cb_track);
        cb_track.setOnCheckedChangeListener(this);

        //鸣叫
        cb_beeping = view.findViewById(R.id.flightsetting_cb_beeping);
        cb_beeping.setOnCheckedChangeListener(this);

        RemoteController remoteController = MyApplication.getRemoteControllerInstance();
        if (remoteController != null) {
            //支持专业自定义控件
//            if (remoteController.isCustomizableButtonSupported()) {
//                ll_professional_custom_controls = findViewById(R.id.flightsetting_ll_professional_custom_controls);
//                ll_professional_custom_controls.setVisibility(VISIBLE);
//                findViewById(R.id.flightsetting_v_professional_custom_controls_splitline).setVisibility(VISIBLE);
//                ll_professional_custom_controls.setOnClickListener(this);
//            }

            //支持主辅控
            if (remoteController.isMasterSlaveModeSupported()) {
                findViewById(R.id.flightsetting_ll_master_slave).setVisibility(VISIBLE);
                //主辅控
                sp_master_slave = view.findViewById(R.id.sp_flight_setting_main_control);
                masterSlaveAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv, master_slave_state, 1, sp_master_slave);
                sp_master_slave.setAdapter(masterSlaveAdapter);
                sp_master_slave.setOnItemSelectedListener(this);
            }

            //支持次级视频
//            if (remoteController.isSecondaryVideoOutputSupported()) {
            findViewById(R.id.flightsetting_ll_secound_video).setVisibility(VISIBLE);
            //视频输出模式
            sp_out_put_mode = view.findViewById(R.id.sp_flight_setting_app_output_mode);
            displayModeAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv,
                    output_mode, 1, sp_out_put_mode);
            displayModeAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
            sp_out_put_mode.setAdapter(displayModeAdapter);
            sp_out_put_mode.setOnItemSelectedListener(this);

            //视频输出格式
            sp_out_put_formate = view.findViewById(R.id.sp_flight_setting_app_output_formate);
            formateAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv,
                    output_formate, 1, sp_out_put_formate);
            formateAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
            sp_out_put_formate.setAdapter(formateAdapter);
            sp_out_put_formate.setOnItemSelectedListener(this);

            //OSD
            view.findViewById(R.id.flightsetting_ll_osd).setOnClickListener(this);
            cb_osd = view.findViewById(R.id.flightsetting_cb_osd);
            cb_osd.setOnCheckedChangeListener(this);

            //画中画
            sp_pip = view.findViewById(R.id.sp_flight_setting_app_output_pip);
            pipAdapter = new SpinnerDropDownAdapter(context, R.layout.item_menu_blank, R.id.tv_item_menu_blank_tv,
                    output_pip, 1, sp_pip);
            pipAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
            sp_pip.setAdapter(pipAdapter);
            sp_pip.setOnItemSelectedListener(this);
//            }
            remoteController.getAircraftMappingStyle(new CommonCallbacks.CompletionCallbackWith<AircraftMappingStyle>() {
                @Override
                public void onSuccess(AircraftMappingStyle aircraftMappingStyle) {
                    if (aircraftMappingStyle.value() == AircraftMappingStyle.STYLE_1.value()) {//STYLE_1为日本手 2美国手 3为中国手
                        OnUIUtils.setCompoundButtonState(rb_jap, true);
                    } else if (aircraftMappingStyle.value() == AircraftMappingStyle.STYLE_2.value()) {
                        OnUIUtils.setCompoundButtonState(rb_usa, true);
                    } else {
                        OnUIUtils.setCompoundButtonState(rb_chn, true);
                    }
                    rb_jap.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            rb_jap.setOnClickListener(FlightSettingLayout.this);
                            rb_usa.setOnClickListener(FlightSettingLayout.this);
                            rb_chn.setOnClickListener(FlightSettingLayout.this);
                        }
                    }, 500);
                }

                @Override
                public void onFailure(DJIError djiError) {

                }
            });
        }

        //信道图
        cl_channelLayout = view.findViewById(R.id.flightsetting_cl_channellayout);
        ll_channel = view.findViewById(R.id.flightsetting_ll_channel);
        ll_channel.setVisibility(rb_manual.isChecked() ? VISIBLE : GONE);
        cl_channelLayout.setOnChannelSelectedListener(new ChannelLayout.OnChannelSelectedListener() {
            @Override
            public void OnChannelSelected(int p) {
                if (rb_manual.isChecked()) {
                    OnUIUtils.setTextView((TextView) view.findViewById(R.id.flightsetting_tv_channel), p + "M");
                    setChannel(p);
                }
            }
        });

        AirLink airLink = MyApplication.getAirLinkInstance();
        if (airLink != null) {
            boolean isLightbridgeLinkSupported = airLink.isLightbridgeLinkSupported();
            if (isLightbridgeLinkSupported) {
                final LightbridgeLink lightbridgeLink = airLink.getLightbridgeLink();
                lightbridgeLink.setChannelInterferenceCallback(new LightbridgeLink.ChannelInterferenceCallback() {
                    @Override
                    public void onResult(ChannelInterference[] cnl) {
                        float[] c = new float[cnl.length];
                        float[] p = new float[cnl.length];
                        for (int i = 0; i < cnl.length; i++) {
                            c[i] = cnl[i].getChannel();
                            p[i] = cnl[i].getPower();
                        }
                        cl_channelLayout.setupValue(c, p);
                        cl_channelLayout.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }

    public void checkSourseInput(){
        AirLink airLink = MyApplication.getAirLinkInstance();
        if (airLink!=null&&airLink.isOcuSyncLinkSupported()) {
            if (cameras.size()>1){
                //有2个相机时设置成左边为主相机，右边为辅相机
                setPhysicalSourse(main_camera_setting,assistant_camera_setting);
            }
            //判断左（或唯一的）相机名称是否含有payload
            String cameraName = cameras.get(0).getDisplayName();
            if (cameraName.contains("payload") || cameraName.contains("PayLoad")
                    || cameraName.contains("Payload")) {
                mActivity.showRedPlus();
            } else {
                mActivity.hideRedPlus();
            }
        }
    }

    /**
     * 设置固定下行链路信道
     */
    private void setChannel(int p) {
        AirLink airLink = MyApplication.getAirLinkInstance();
        if (airLink != null) {
            boolean isLightbridgeLinkSupported = airLink.isLightbridgeLinkSupported();
            if (isLightbridgeLinkSupported) {
                final LightbridgeLink lightbridgeLink = airLink.getLightbridgeLink();
                lightbridgeLink.setChannelNumber(p, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null)
                            OnUIUtils.setToast(djiError.getDescription());
                    }
                });
            }
        }
    }

    private int getStringArrayIndex(String[] array, String arg) {
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(arg)) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 设置选择的Layout
     */
    private void chooseLayout(int tag) {
        if (tag == lastPage / 10)
            return;
        changeBackground(tag, lastPage / 10);

        if (layouts[tag].getVisibility() != View.VISIBLE) {
            layouts[tag].setVisibility(View.VISIBLE);
            firstLayout = layouts[tag];
        }
        if (layouts[lastPage / 10].getVisibility() == View.VISIBLE)
            layouts[lastPage / 10].setVisibility(View.GONE);

        setVisiLayout(tag * 10, false);
    }

    private void changeBackground(int tag, int i) {
        switch (tag) {
            case 0:
                view.findViewById(R.id.flightsetting_v_0).setBackgroundResource(R.drawable.setting_aircraft_hover_ic);
                break;
            case 1:
                view.findViewById(R.id.flightsetting_v_1).setBackgroundResource(R.drawable.setting_vision_hover_ic);
                break;
            case 2:
                view.findViewById(R.id.flightsetting_v_2).setBackgroundResource(R.drawable.setting_rc_hover_ic);
                break;
            case 3:
                view.findViewById(R.id.flightsetting_v_3).setBackgroundResource(R.drawable.setting_hd_hover_ic);
                break;
            case 4:
                view.findViewById(R.id.flightsetting_v_4).setBackgroundResource(R.drawable.setting_battery_hover_ic);
                break;
            case 5:
                view.findViewById(R.id.flightsetting_v_5).setBackgroundResource(R.drawable.setting_gimbal_hover_ic);
                break;
            case 6:
                view.findViewById(R.id.flightsetting_v_6).setBackgroundResource(R.drawable.setting_more_hover_ic);
                break;
            case 7:
                view.findViewById(R.id.flightsetting_v_7).setBackgroundResource(R.drawable.setting_watcher_hover_ic);
                break;
        }
        switch (i) {
            case 0:
                view.findViewById(R.id.flightsetting_v_0).setBackgroundResource(R.drawable.setting_aircraft_nor_ic);
                break;
            case 1:
                view.findViewById(R.id.flightsetting_v_1).setBackgroundResource(R.drawable.setting_vision_nor_ic);
                break;
            case 2:
                view.findViewById(R.id.flightsetting_v_2).setBackgroundResource(R.drawable.setting_rc_nor_ic);
                break;
            case 3:
                view.findViewById(R.id.flightsetting_v_3).setBackgroundResource(R.drawable.setting_hd_nor_ic);
                break;
            case 4:
                view.findViewById(R.id.flightsetting_v_4).setBackgroundResource(R.drawable.setting_battery_nor_ic);
                break;
            case 5:
                view.findViewById(R.id.flightsetting_v_5).setBackgroundResource(R.drawable.setting_gimbal_nor_ic);
                break;
            case 6:
                view.findViewById(R.id.flightsetting_v_6).setBackgroundResource(R.drawable.setting_more_nor_ic);
                break;
            case 7:
                view.findViewById(R.id.flightsetting_v_7).setBackgroundResource(R.drawable.setting_watcher_ic);
                break;
        }
    }

    private void setVisiLayout(int targetPage, boolean doAnim) {
        if (targetPage % 10 != 0) {
            firstLayout.setVisibility(GONE);
//            AnimUtils.setHideAnimation(firstLayout, 100);
            secondLayout.setVisibility(VISIBLE);
            secondLayout.setAnimation(AnimationUtils.makeInAnimation(context, false));
            fl_title_back.setVisibility(VISIBLE);
        } else if (lastPage % 10 != 0) {
            secondLayout.setVisibility(GONE);
            firstLayout.setVisibility(VISIBLE);
            if (doAnim) {
                secondLayout.setAnimation(AnimationUtils.makeOutAnimation(context, true));
                AnimUtils.setShowAnimation(firstLayout, 500);
            }
            fl_title_back.setVisibility(GONE);
        }

        lastPage = targetPage;

        switch (targetPage) {
            case 0:
                tv_title.setText(R.string.flightsetting_flight_control);
                break;
            case 1:
                tv_title.setText(R.string.flightsetting_2_sensor_state);
                break;
            case 10:
                tv_title.setText(R.string.flightsetting_perception);
                break;
            case 20:
                tv_title.setText(R.string.flightsetting_remote_control);
                break;
            case 21:
                tv_title.setText(R.string.flightsetting_2_rocker_mode);
                break;
            case 30:
                tv_title.setText(R.string.flightsetting_send_pictures);
                break;
            case 31:
                tv_title.setText(R.string.flightsetting_2_camera_select);
                break;
            case 32:
                tv_title.setText(R.string.flightsetting_2_osd);
                break;
            case 40:
                tv_title.setText(R.string.flightsetting_smart_battery);
                break;
            case 41:
                tv_title.setText(R.string.flightsetting_2_battery_info);
                break;
            case 50:
                tv_title.setText(R.string.flightsetting_ptz);
                break;
            case 60:
                tv_title.setText(R.string.flightsetting_common);
                break;
            case 61:
                tv_title.setText(R.string.flightsetting_2_devicename);
                break;
            case 62:
                tv_title.setText(R.string.flightsetting_2_about);
                break;
            case 70:
                tv_title.setText(R.string.flightsetting_payload);
                break;
        }
    }

    /**
     * seekBar callback
     */
    @SuppressLint("StringFormatInvalid")
    @Override
    public void onProgressChanged(SeekBar seekBar, int p, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.flightsetting_sb_bandwidth:
                tv_bandwidth_hdmi.setText(getResources().getString(R.string.flightsetting_bandwidth_hdmi, p));
                tv_bandwidth_av.setText(getResources().getString(R.string.flightsetting_bandwidth_av, 100 - p));
                break;
            case R.id.flightsetting_sb_serious_lowbattery_warning:
                tv_serious_lowbattery_warning.setText(getResources().getString(R.string.percentage, 10 + p));
                break;
            case R.id.flightsetting_sb_lowbattery_warning:
                tv_lowbattery_warning.setText(getResources().getString(R.string.percentage, 15 + p));
                break;
            case R.id.flightsetting_sb_osd_top:
                pct_top.setText(getResources().getString(R.string.percentage, p));
                break;
            case R.id.flightsetting_sb_osd_left:
                pct_left.setText(getResources().getString(R.string.percentage, p));
                break;
            case R.id.flightsetting_sb_osd_bottom:
                pct_bottom.setText(getResources().getString(R.string.percentage, p));
                break;
            case R.id.flightsetting_sb_osd_right:
                pct_right.setText(getResources().getString(R.string.percentage, p));
                break;

        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        switch (seekBar.getId()) {
            case R.id.flightsetting_sb_bandwidth:
                initProgress = sb_bandwidth.getProgress();
                break;
            case R.id.flightsetting_sb_serious_lowbattery_warning:
                initProgress = sb_serious_lowbattery_warning.getProgress();
                break;
            case R.id.flightsetting_sb_lowbattery_warning:
                initProgress = sb_lowbattery_warning.getProgress();
                break;
            case R.id.flightsetting_sb_osd_top:
                initProgress = sb_top.getProgress();
                break;
            case R.id.flightsetting_sb_osd_left:
                initProgress = sb_left.getProgress();
                break;
            case R.id.flightsetting_sb_osd_bottom:
                initProgress = sb_bottom.getProgress();
                break;
            case R.id.flightsetting_sb_osd_right:
                initProgress = sb_right.getProgress();
                break;
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        switch (seekBar.getId()) {
            case R.id.flightsetting_sb_bandwidth:
                setBandwidthAllocation(sb_bandwidth.getProgress());
                break;
            case R.id.flightsetting_sb_serious_lowbattery_warning:
                setSeriousLowBatteryWarning(sb_serious_lowbattery_warning.getProgress() + 10);
                break;
            case R.id.flightsetting_sb_lowbattery_warning:
                setLowBatteryWarning(sb_lowbattery_warning.getProgress() + 15);
                break;
            case R.id.flightsetting_sb_osd_top:
                setOSDMargin(0, sb_top.getProgress());
                break;
            case R.id.flightsetting_sb_osd_left:
                setOSDMargin(1, sb_left.getProgress());
                break;
            case R.id.flightsetting_sb_osd_bottom:
                setOSDMargin(2, sb_bottom.getProgress());
                break;
            case R.id.flightsetting_sb_osd_right:
                setOSDMargin(3, sb_right.getProgress());
                break;
        }
    }

    /**
     * 设置OSD边距
     */
    private void setOSDMargin(int step, int progress) {
        RemoteController remoteController = MyApplication.getRemoteControllerInstance();
        if (remoteController == null)
            return;
        switch (step) {
            case 0:
                remoteController.setSecondaryVideoOSDTopMargin(progress, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setProgressBarProgress(sb_top, initProgress);
                        }
                    }
                });
                break;
            case 1:
                remoteController.setSecondaryVideoOSDLeftMargin(progress, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setProgressBarProgress(sb_left, initProgress);
                        }
                    }
                });
                break;
            case 2:
                remoteController.setSecondaryVideoOSDBottomMargin(progress, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setProgressBarProgress(sb_bottom, initProgress);
                        }
                    }
                });
                break;
            case 3:
                remoteController.setSecondaryVideoOSDRightMargin(progress, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setProgressBarProgress(sb_right, initProgress);
                        }
                    }
                });
                break;
        }
    }

    /**
     * 编辑执行完成回调
     */
    private OnEditFinishListener finishListener;

    public interface OnEditFinishListener {
        void onFinish();
    }

    public void setOnEditFinnshListener(OnEditFinishListener cb) {
        finishListener = cb;
    }

    /**
     * Dialog消失监听
     */
    @Override
    public void onDismiss(DialogInterface dialog) {
        if (finishListener != null)
            finishListener.onFinish();
    }

    /**
     * 点击
     */
    @Override
    public void onClick(View v) {
        CommomDialog commomDialog;
        switch (v.getId()) {
            case R.id.flightsetting_fl_0:
            case R.id.flightsetting_fl_1:
            case R.id.flightsetting_fl_2:
            case R.id.flightsetting_fl_3:
            case R.id.flightsetting_fl_4:
            case R.id.flightsetting_fl_5:
            case R.id.flightsetting_fl_6:
            case R.id.flightsetting_fl_7:
                String entryName = getResources().getResourceEntryName(v.getId());
                chooseLayout(Integer.parseInt(entryName.substring(entryName.length() - 1, entryName.length())));
                break;
            case R.id.flightsetting_fl_title_cancel:
                setVisibility(GONE);
                setAnimation(AnimationUtils.makeOutAnimation(context, true));
                break;
            case R.id.flightsetting_fl_title_back:
                setVisiLayout(lastPage / 10 * 10, true);
                break;
            case R.id.flightsetting_ll_sensor_state:
                secondLayout = view.findViewById(R.id.flightsetting_ll_2_sensor_mode);
                setVisiLayout(lastPage + 1, true);
                break;
            case R.id.flightsetting_ll_rocker_mode:
                secondLayout = view.findViewById(R.id.flightsetting_ll_2_rocker_mode);
                setVisiLayout(lastPage + 1, true);
                break;
            case R.id.flightsetting_ll_camera_select:
                secondLayout = view.findViewById(R.id.flightsetting_ll_2_camera_select);
                setVisiLayout(lastPage + 1, true);
                break;
            case R.id.flightsetting_ll_osd:
                secondLayout = view.findViewById(R.id.flightsetting_ll_2_osd);
                setVisiLayout(lastPage + 2, true);
                getOSDState();
                break;
            case R.id.flightsetting_ll_battery_info:
                secondLayout = view.findViewById(R.id.flightsetting_ll_2_battery_info);
                setVisiLayout(lastPage + 1, true);
                break;
            case R.id.flightsetting_ll_devicename:
                secondLayout = view.findViewById(R.id.flightsetting_ll_2_devicename);
                setVisiLayout(lastPage + 1, true);
                getDeviceName();
                break;
            case R.id.flightsetting_ll_about:
                secondLayout = view.findViewById(R.id.flightsetting_ll_2_about);
                setVisiLayout(lastPage + 2, true);
                break;
            case R.id.flightsetting_ll_live_stream://直播
                secondLayout = view.findViewById(R.id.flightsetting_ll_2_live_stream);
                setVisiLayout(lastPage + 3, true);
                break;
            case R.id.flightsetting_ll_2_live_stream:
                showRTMPSettingDialog();
                break;
            case R.id.flightsetting_tv_calibration_imu:
                BaseProduct product = MyApplication.getProductInstance();
                if (product == null || !product.isConnected()) {
                    Toast.makeText(context, "请检查设备是否连接", Toast.LENGTH_SHORT).show();
                    return;
                }
                IMUDialog IMUDialog = new IMUDialog(context);
                IMUDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        //重设监听
                        FlightController flightController = MyApplication.getFlightControllerInstance();
                        if (flightController == null)
                            return;
                        flightController.setIMUStateCallback(FlightSettingLayout.this);
                        if (finishListener != null)
                            finishListener.onFinish();
                    }
                });
                IMUDialog.show();
                break;
            case R.id.flightsetting_tv_calibration_compass:
                final FlightController flightController = MyApplication.getFlightControllerInstance();
                if (flightController == null || !flightController.isConnected()) {
                    Toast.makeText(context, "请检查设备是否连接", Toast.LENGTH_SHORT).show();
                    return;
                }

                commomDialog = new CommomDialog(context, R.style.commondialog, "请确定是否要开始校准指南针。",
                        new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(CommomDialog dialog, boolean confirm) {
                                if (confirm) {
                                    //校准控件
//                                    new CompassCalibratingWorkFlow(context).showImgDlg();
                                    //校准函数
                                    flightController.getCompass().startCalibration(new CommonCallbacks.CompletionCallback() {
                                        @Override
                                        public void onResult(DJIError djiError) {
                                            if (djiError != null) {
                                                OnUIUtils.setToast("启动失败");

                                            }
                                        }
                                    });
                                }
                                dialog.dismiss();
                            }
                        });
                commomDialog.setOnDismissListener(this);
                commomDialog.show();

                //自定义
//                CompassDialog compassDialog = new CompassDialog(context, flightController.getCompass());
//                compassDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//                    @Override
//                    public void onDismiss(DialogInterface dialog) {
//                        flightController.getCompass().setCalibrationStateCallback(null);
//                        if (finishListener != null)
//                            finishListener.onFinish();
//                    }
//                });
//                compassDialog.show();
                break;
            case R.id.flightsetting_tv_remote_pairing:
                commomDialog = new CommomDialog(context, R.style.commondialog, "请确定是否要进行对频。",
                        new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(CommomDialog dialog, boolean confirm) {
                                if (confirm) {
                                    startRemotePairing();
                                }
                                dialog.dismiss();
                            }
                        });
                commomDialog.setOnDismissListener(this);
                commomDialog.show();
                break;
            case R.id.flightsetting_tv_reset_gimbal:
                commomDialog = new CommomDialog(context, R.style.commondialog, "请确定是否要重置云台参数",
                        new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(CommomDialog dialog, boolean confirm) {
                                if (confirm) {
                                    restoreGimbalFactorySettings();
                                }
                                dialog.dismiss();
                            }
                        });
                commomDialog.setOnDismissListener(this);
                commomDialog.show();
                break;
            case R.id.flightsetting_tv_gimbal_autocalibration:
                commomDialog = new CommomDialog(context, R.style.commondialog, "请确保您的飞机在地面上，并保持水平，按确定后云台将开始自动校准",
                        new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(CommomDialog dialog, boolean confirm) {
                                if (confirm) {
                                    gimbalCalibration();
                                }
                                dialog.dismiss();
                            }
                        });
                commomDialog.setOnDismissListener(this);
                commomDialog.show();
                break;
            case R.id.flightsetting_tv_homepoint_craft_location:
                commomDialog = new CommomDialog(context, R.style.commondialog, "设置当前飞机位置为返航点，如果需要时，返航时飞机将会适当调整高度并以不低于30m（98.4ft）的高度返航请留意地图返航位置更新。",
                        new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(CommomDialog dialog, boolean confirm) {
                                if (confirm) {
                                    setRTHLocation(true);
                                }
                                dialog.dismiss();
                            }
                        }).setTitle("设置当前飞机位置为返航点");
                commomDialog.setOnDismissListener(this);
                commomDialog.show();
                break;
            case R.id.flightsetting_tv_homepoint_home_location:
                commomDialog = new CommomDialog(context, R.style.commondialog, "设置操作者当前位置为返航点，请确保已授权使用移动设备GPS信息并确认GPS信号良好。",
                        new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(CommomDialog dialog, boolean confirm) {
                                if (confirm) {
                                    if (mPref.getBoolean("mobile_gps", false)) {
                                        setRTHLocation(false);
                                    } else {
                                        Toast.makeText(context, "请授权使用手机GPS信息", Toast.LENGTH_SHORT).show();
                                    }
                                }
                                dialog.dismiss();
                            }
                        });
                commomDialog.setOnDismissListener(this);
                commomDialog.show();
                break;
            case R.id.flightsetting_tv_save_devicename:
                String lastName = et_devicename.getText().toString();
                if (TextUtils.isEmpty(lastName)) {
                    Toast.makeText(context, "名字不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                setDeviceName(lastName);
                break;
//            case R.id.flightsetting_tv_update_craft:
//
//                break;
//            case R.id.flightsetting_tv_update_app:
//
//                break;
//            case R.id.flightsetting_tv_update_base:
//
//                break;
            case R.id.flightsetting_ll_professional_custom_controls:
                context.startActivity(new Intent(context, ControllerSettingActivity.class));
                break;
            case R.id.flightsetting_rb_jap:
                RemoteController remoteController1 = MyApplication.getRemoteControllerInstance();
                if (remoteController1 != null) {
                    remoteController1.setAircraftMappingStyle(AircraftMappingStyle.STYLE_1, new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.toString());
                            }
                        }
                    });
                }
                break;
            case R.id.flightsetting_rb_usa:
                RemoteController remoteController2 = MyApplication.getRemoteControllerInstance();
                if (remoteController2 != null) {
                    remoteController2.setAircraftMappingStyle(AircraftMappingStyle.STYLE_2, new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.toString());
                            }
                        }
                    });
                }
                break;
            case R.id.flightsetting_rb_chn:
                RemoteController remoteController3 = MyApplication.getRemoteControllerInstance();
                if (remoteController3 != null) {
                    remoteController3.setAircraftMappingStyle(AircraftMappingStyle.STYLE_3, new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.toString());
                            }
                        }
                    });
                }
                break;
            case R.id.btn_change_sourse_input:
                if (main_camera_setting == assistant_camera_setting) {
                    OnUIUtils.setToast("主辅相机不能相同！");
                    return;
                }
                setPhysicalSourse(main_camera_setting, assistant_camera_setting);
                break;
        }
    }

    /**
     * 获取OSD是否开启
     */
    private void getOSDState() {
        RemoteController remoteController = MyApplication.getRemoteControllerInstance();
        if (remoteController == null)
            return;
        remoteController.getSecondaryVideoOSDEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                OnUIUtils.setCompoundButtonState(cb_osd, aBoolean);
            }

            @Override
            public void onFailure(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_osd, false);
                }
            }
        });
    }

    private void showRTMPSettingDialog() {
        CommomDialog dialog = new CommomDialog(context, R.style.commondialog, "", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(CommomDialog dialog, boolean confirm) {
                if (confirm) {
                    BaseProduct product = MyApplication.getProductInstance();
                    if (product == null) {
                        OnUIUtils.setToast("相机不可用，请检查相机");
                        return;
                    }
                    List<Camera> cameras = product.getCameras();
                    if (cameras.size() > 0) {
                        String url = dialog.getEditTextContent();
                        if (!"".equals(url)) {
                            //新建自定义直播 TODO
                            LiveStreamManager manager = DJISDKManager.getInstance().getLiveStreamManager();
                            manager.setLiveUrl(url);
                            int result = manager.startStream();
                        }


                    } else {
                        OnUIUtils.setToast("相机不可用，请检查相机");
                    }
                }
            }
        });
//        dialog.show();
        dialog.show();
        dialog.showEdittext("rtmp://").setTitle("自定义直播链接");
    }

    /**
     * RadioGroup
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        AirLink airLink;
        //信道
        if (group == rg_channel_choice) {
            if (checkedId == rb_automatic.getId()) {
                airLink = MyApplication.getAirLinkInstance();
                if (airLink == null)
                    return;
                if (!airLink.isLightbridgeLinkSupported()) {
                    rb_automatic.setChecked(true);
                    Toast.makeText(context, "不支持 Lightbridge Air Link", Toast.LENGTH_SHORT).show();
                    return;
                }
                setChannelSelectionMode(false);
                ll_channel.setVisibility(GONE);
            } else if (checkedId == rb_manual.getId()) {
                airLink = MyApplication.getAirLinkInstance();
                if (airLink == null)
                    return;
                if (!airLink.isLightbridgeLinkSupported()) {
                    rb_automatic.setChecked(true);
                    Toast.makeText(context, "不支持 Lightbridge Air Link", Toast.LENGTH_SHORT).show();
                    return;
                }
                setChannelSelectionMode(true);
                ll_channel.setVisibility(VISIBLE);
            }
        } else
            //传感器
            if (group == rg_sensor) {
                if (checkedId == rb_imu.getId()) {
                    ll_compass.setVisibility(GONE);
                    ll_imu.setVisibility(VISIBLE);
                } else if (checkedId == rb_compass.getId()) {
                    ll_imu.setVisibility(GONE);
                    ll_compass.setVisibility(VISIBLE);
                }

            } else
                //摇杆模式
                if (group == rg_gesture) {
                    if (lastRB != null) {
                        if (checkedId != lastRB.getId()) {
                            new CommomDialog(context, R.style.commondialog, "请确定是否熟悉该摇杆操作模式，切换将改变原有控制逻辑，请谨慎操作。",
                                    new CommomDialog.OnCloseListener() {
                                        @Override
                                        public void onClick(CommomDialog dialog, boolean confirm) {
                                            if (confirm) {
//                                            Toast.makeText(context, "暂不支持更换模式", Toast.LENGTH_SHORT).show();
//                                            lastRB.setChecked(true);
                                                lastRB = curRB;
                                            } else {
                                                lastRB.setChecked(true);
                                            }
                                            dialog.dismiss();
                                            if (finishListener != null)
                                                finishListener.onFinish();
                                        }
                                    }).show();

                        }
                    }
                    if (checkedId == rb_usa.getId()) {
                        view.findViewById(R.id.flightsetting_v_gesture_pic).setBackgroundResource(R.drawable.pic_usa_hand);
                        curRB = rb_usa;
                    } else if (checkedId == rb_jap.getId()) {
                        view.findViewById(R.id.flightsetting_v_gesture_pic).setBackgroundResource(R.drawable.pic_jap_hand);
                        curRB = rb_jap;
                    } else if (checkedId == rb_chn.getId()) {
                        view.findViewById(R.id.flightsetting_v_gesture_pic).setBackgroundResource(R.drawable.pic_chn_hand);
                        curRB = rb_chn;
                    }
                }
    }

    /**
     * CheckBox
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        FlightController flightController;
        AirLink airLink;
        switch (buttonView.getId()) {
            case R.id.flightsetting_cb_flightmode:
                setFlightModeChangeability(isChecked);
                break;
            case R.id.flightsetting_cb_maxradius:
                setMaxRadius(isChecked);
                break;
            case R.id.flightsetting_cb_tripodmode:
                setTripodMode(isChecked);
                break;
            case R.id.flightsetting_cb_gear:
                flightController = MyApplication.getFlightControllerInstance();
                if (flightController == null)
                    return;
                if (!flightController.isLandingGearMovable()) {
                    cb_gear.setChecked(false);
                    Toast.makeText(context, "连接的飞机不支持起落架", Toast.LENGTH_SHORT).show();
                    return;
                }
                setAutomaticMovement(isChecked);
                break;
            case R.id.flightsetting_cb_collision_avoidance:
                flightController = MyApplication.getFlightControllerInstance();
                if (flightController == null)
                    return;
                if (!flightController.isFlightAssistantSupported()) {
                    cb_collision_avoidance.setChecked(false);
                    Toast.makeText(context, "智能飞行保护系统不可用", Toast.LENGTH_SHORT).show();
                    return;
                }
                setCollisionAvoidance(isChecked);
                if (isChecked) {
                    cb_rth_avoidance.setChecked(true);
//                    setRTHObstacleAvoidance(true);
                }
                break;
            case R.id.flightsetting_cb_landing_protection:
                flightController = MyApplication.getFlightControllerInstance();
                if (flightController == null)
                    return;
                if (!flightController.isFlightAssistantSupported()) {
                    cb_collision_avoidance.setChecked(false);
                    Toast.makeText(context, "智能飞行保护系统不可用", Toast.LENGTH_SHORT).show();
                    return;
                }
                setLandProtection(isChecked);
                break;
            case R.id.flightsetting_cb_rth_avoidance:
                flightController = MyApplication.getFlightControllerInstance();
                if (flightController == null)
                    return;
                if (!flightController.isFlightAssistantSupported()) {
                    cb_collision_avoidance.setChecked(false);
                    Toast.makeText(context, "智能飞行保护系统不可用", Toast.LENGTH_SHORT).show();
                    return;
                }
                setRTHObstacleAvoidance(isChecked);
                if (!isChecked) {
                    cb_collision_avoidance.setChecked(false);
                    setCollisionAvoidance(false);
                }
                break;
            case R.id.flightsetting_cb_ext_port:
                airLink = MyApplication.getAirLinkInstance();
                if (airLink == null)
                    return;
                if (!airLink.isLightbridgeLinkSupported()) {
                    rb_automatic.setChecked(true);
                    Toast.makeText(context, "不支持 Lightbridge Air Link", Toast.LENGTH_SHORT).show();
                    return;
                }
                setEXTPort(isChecked);
                break;
            case R.id.flightsetting_cb_smart_rth:
                setSmartRTH(isChecked);
                break;
            case R.id.flightsetting_cb_gimbal_limit:
                setPitchRangeExtensionEnabled(isChecked);
                break;
            case R.id.flightsetting_cb_radar:
                if (radarListener != null)
                    radarListener.onChanged(cb_radar.isChecked());
                break;
            case R.id.flightsetting_cb_track:
                if (trackListener != null)
                    trackListener.onChanged(cb_track.isChecked());
                break;
            case R.id.flightsetting_cb_beeping:
                setECSBeeping(isChecked);
                break;
            case R.id.flightsetting_cb_osd:
                view.findViewById(R.id.flightsetting_rl_osd_info).setVisibility(isChecked ? VISIBLE : GONE);
                if (isChecked)
                    initOSD();
                break;

        }
    }

    private void initOSD() {
        RemoteController remoteController = MyApplication.getRemoteControllerInstance();
        if (remoteController == null)
            return;

        sb_top = findViewById(R.id.flightsetting_sb_osd_top);
        sb_top.setOnSeekBarChangeListener(this);
        sb_left = findViewById(R.id.flightsetting_sb_osd_left);
        sb_left.setOnSeekBarChangeListener(this);
        sb_bottom = findViewById(R.id.flightsetting_sb_osd_bottom);
        sb_bottom.setOnSeekBarChangeListener(this);
        sb_right = findViewById(R.id.flightsetting_sb_osd_right);
        sb_right.setOnSeekBarChangeListener(this);
        pct_top = findViewById(R.id.flightsetting_tv_osd_pct_top);
        pct_left = findViewById(R.id.flightsetting_tv_osd_pct_left);
        pct_bottom = findViewById(R.id.flightsetting_tv_osd_pct_bottom);
        pct_right = findViewById(R.id.flightsetting_tv_osd_pct_right);

        remoteController.getSecondaryVideoOSDTopMargin(new CommonCallbacks.CompletionCallbackWith<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                OnUIUtils.setSeekbarProgress(sb_top, integer);
                OnUIUtils.setTextView(pct_top, view.getResources().getString(R.string.percentage, integer));
            }

            @Override
            public void onFailure(DJIError djiError) {
                OnUIUtils.setSeekbarProgress(sb_top, 0);
                OnUIUtils.setTextView(pct_top, view.getResources().getString(R.string.percentage, 0));
            }
        });

        remoteController.getSecondaryVideoOSDLeftMargin(new CommonCallbacks.CompletionCallbackWith<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                OnUIUtils.setSeekbarProgress(sb_left, integer);
                OnUIUtils.setTextView(pct_left, view.getResources().getString(R.string.percentage, integer));
            }

            @Override
            public void onFailure(DJIError djiError) {
                OnUIUtils.setSeekbarProgress(sb_left, 0);
                OnUIUtils.setTextView(pct_left, view.getResources().getString(R.string.percentage, 0));
            }
        });

        remoteController.getSecondaryVideoOSDBottomMargin(new CommonCallbacks.CompletionCallbackWith<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                OnUIUtils.setSeekbarProgress(sb_bottom, integer);
                OnUIUtils.setTextView(pct_bottom, view.getResources().getString(R.string.percentage, integer));
            }

            @Override
            public void onFailure(DJIError djiError) {
                OnUIUtils.setSeekbarProgress(sb_bottom, 0);
                OnUIUtils.setTextView(pct_bottom, view.getResources().getString(R.string.percentage, 0));
            }
        });
        remoteController.getSecondaryVideoOSDRightMargin(new CommonCallbacks.CompletionCallbackWith<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                OnUIUtils.setSeekbarProgress(sb_right, integer);
                OnUIUtils.setTextView(pct_right, view.getResources().getString(R.string.percentage, integer));
            }

            @Override
            public void onFailure(DJIError djiError) {
                OnUIUtils.setSeekbarProgress(sb_right, 0);
                OnUIUtils.setTextView(pct_right, view.getResources().getString(R.string.percentage, 0));
            }
        });


    }

    /**
     * 蜂鸣
     */
    private void setECSBeeping(final boolean isChecked) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setESCBeepEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_beeping, !isChecked);
                }
            }
        });
    }

    /**
     * 雷达显示状态回调
     */
    private OnRadarListener radarListener;

    public interface OnRadarListener {
        void onChanged(boolean b);
    }

    public void setOnRadarListener(OnRadarListener cb) {
        radarListener = cb;
    }

    /**
     * 航迹显示状态回调
     */
    private OnTrackListener trackListener;

    public interface OnTrackListener {
        void onChanged(boolean b);
    }

    public void setOnTrackListener(OnTrackListener cb) {
        trackListener = cb;
    }

    /**
     * 云台俯仰拓展
     */
    private void setPitchRangeExtensionEnabled(final boolean isChecked) {
        List<Gimbal> gimbalList = MyApplication.getGimbalInstance();
        if (gimbalList == null || gimbalList.size() <= 0) {
            Toast.makeText(context, "未连接到设备", Toast.LENGTH_SHORT).show();
            return;
        }
        for (int i = 0; i < gimbalList.size(); i++) {
            Gimbal gimbal = gimbalList.get(i);
            if (gimbal == null)
                return;
            gimbal.setPitchRangeExtensionEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setCompoundButtonState(cb_gimbal_limit, !isChecked);
                    }
                }
            });
        }
    }

    /**
     * 设置设备名称
     */
    private void setDeviceName(String lastName) {
        Aircraft aircraft = (Aircraft) MyApplication.getProductInstance();
        if (aircraft == null) {
            Toast.makeText(context, "未连接到设备", Toast.LENGTH_SHORT).show();
            return;
        }
        aircraft.setName(lastName, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                }
            }
        });
    }

    /**
     * 获取设备名称
     */
    private void getDeviceName() {
        Aircraft aircraft = (Aircraft) MyApplication.getProductInstance();
        if (aircraft == null)
            return;
        aircraft.getName(new CommonCallbacks.CompletionCallbackWith<String>() {
            @Override
            public void onSuccess(String s) {
                OnUIUtils.setEditViewText(et_devicename, s);
            }

            @Override
            public void onFailure(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                }
            }
        });
    }

    /**
     * 设置返航点
     */
    private void setRTHLocation(boolean isCraftLocation) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null) {
            Toast.makeText(context, "未连接到设备", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isCraftLocation) {
            flightController.setHomeLocationUsingAircraftCurrentLocation(new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                    } else {
                        OnUIUtils.setToast("设置成功");
                    }
                }
            });
        } else {
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            if (locationManager == null)
                return;
            if (ActivityCompat.checkSelfPermission(context,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            flightController.setHomeLocation(new LocationCoordinate2D(location.getLatitude(), location.getLongitude()),
                    new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.getDescription());
                            } else {
                                OnUIUtils.setToast("设置成功");
                            }
                        }
                    });
        }


    }

    /**
     * 云台较准
     */
    private void gimbalCalibration() {
        List<Gimbal> gimbalList = MyApplication.getGimbalInstance();
        if (gimbalList == null) {
            Toast.makeText(context, "未连接到设备", Toast.LENGTH_SHORT).show();
            return;
        }
        for (int i = 0; i < gimbalList.size(); i++) {
            Gimbal gimbal = gimbalList.get(i);
            if (gimbal == null)
                return;
            final int finalI = i;
            gimbal.startCalibration(new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError djiError) {
                    if (djiError == null) {
                        OnUIUtils.setToast(finalI + "号云台校准成功");
                    } else {
                        OnUIUtils.setToast(finalI + "号云台校准失败：" + djiError.getDescription());
                    }
                }
            });

        }
    }

    /**
     * 重置云台参数
     */
    private void restoreGimbalFactorySettings() {
        List<Gimbal> gimbalList = MyApplication.getGimbalInstance();
        if (gimbalList == null) {
            Toast.makeText(context, "未连接到设备", Toast.LENGTH_SHORT).show();
            return;
        }
        for (int i = 0; i < gimbalList.size(); i++) {
            Gimbal gimbal = gimbalList.get(i);
            if (gimbal == null)
                return;
            final int finalI = i;
            gimbal.restoreFactorySettings(new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError djiError) {
                    if (djiError == null) {
                        OnUIUtils.setToast(finalI + "号云台重置成功");
                    } else {
                        OnUIUtils.setToast(finalI + "号云台重置失败：" + djiError.getDescription());
                    }
                }
            });
        }
    }

    /**
     * 开始遥控器匹配
     */
    private void startRemotePairing() {
        final RemoteController remoteController = MyApplication.getRemoteControllerInstance();
        if (remoteController == null) {
            Toast.makeText(context, "未连接到设备", Toast.LENGTH_SHORT).show();
            return;
        }
        remoteController.startPairing(new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                }
            }
        });

    }

    /**
     * 获取传感器状态
     */
    private String getSensorState(SensorState state) {
        String res = "";
        if (state == null)
            return res;
        switch (state.value()) {
            case 255:
                res = "未知";
                break;
            case 1:
                res = "未连接";
                break;
            case 2:
                res = "正在校准";
                break;
            case 3:
                res = "校准失败";
                break;
            case 4:
                res = "数据异常";
                break;
            case 5:
                res = "正在预热";
                break;
            case 6:
                res = "设备不稳定";
                break;
            case 7:
                res = "正常偏差";
                break;
            case 8:
                res = "中等偏差";
                break;
            case 9:
                res = "很大偏差";
                break;
        }
        return res;
    }

    /**
     * 严重低电量报警
     */
    private void setLowBatteryWarning(int i) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setLowBatteryWarningThreshold(i, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setSeekbarProgress(sb_serious_lowbattery_warning, initProgress + 15);
                }
            }
        });
    }

    /**
     * 严重低电量报警
     */
    private void setSeriousLowBatteryWarning(int i) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setSeriousLowBatteryWarningThreshold(i, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setSeekbarProgress(sb_serious_lowbattery_warning, initProgress + 10);
                }
            }
        });
    }

    /**
     * 智能返航
     */
    private void setSmartRTH(final boolean isChecked) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setSmartReturnToHomeEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_smart_rth, !isChecked);
                }
            }
        });
    }

    /**
     * 设置带宽分配
     */
    private void setBandwidthAllocation(int progress) {
        AirLink airLink = MyApplication.getAirLinkInstance();
        if (airLink == null)
            return;
        if (!airLink.getLightbridgeLink().isDualEncodeModeSupported()) {
            Toast.makeText(context, "不支持双编码模式", Toast.LENGTH_SHORT).show();
            return;
        }
        airLink.getLightbridgeLink().setBandwidthAllocationForHDMIVideoInputPort(progress, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setSeekbarProgress(sb_bandwidth, initProgress);
                }
            }
        });
    }

    /**
     * EXT端口
     */
    private void setEXTPort(final boolean isChecked) {
        AirLink airLink = MyApplication.getAirLinkInstance();
        if (airLink == null)
            return;
        airLink.getLightbridgeLink().setEXTVideoInputPortEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_ext_port, !isChecked);
                }
            }
        });
    }

    /**
     * 信道模式
     *
     * @param isManual 是否手动模式
     */
    private void setChannelSelectionMode(boolean isManual) {
        AirLink airLink = MyApplication.getAirLinkInstance();
        if (airLink == null)
            return;
        airLink.getLightbridgeLink().setChannelSelectionMode(isManual ? ChannelSelectionMode.MANUAL : ChannelSelectionMode.AUTO,
                new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setCompoundButtonState(rb_automatic, true);
                        }
                    }
                });
    }

    /**
     * 返航避障
     */
    private void setRTHObstacleAvoidance(final boolean isChecked) {
        if (MyApplication.getFlightControllerInstance() == null)
            return;
        FlightAssistant flightAssistant = MyApplication.getFlightControllerInstance().getFlightAssistant();
        if (flightAssistant == null)
            return;
        flightAssistant.setRTHObstacleAvoidanceEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_rth_avoidance, !isChecked);
                    OnUIUtils.setCompoundButtonState(cb_collision_avoidance, !isChecked);
                    setCollisionAvoidance(false);
                }
            }
        });
    }

    /**
     * 下视视觉
     * 着陆保护
     */
    private void setLandProtection(final boolean isChecked) {
        if (MyApplication.getFlightControllerInstance() == null)
            return;
        FlightAssistant flightAssistant = MyApplication.getFlightControllerInstance().getFlightAssistant();
        if (flightAssistant == null)
            return;
        flightAssistant.setLandingProtectionEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_landing_protection, !isChecked);
                }
            }
        });
    }

    /**
     * 视觉避障系统
     */
    private void setCollisionAvoidance(final boolean isChecked) {
        if (MyApplication.getFlightControllerInstance() == null)
            return;
        FlightAssistant flightAssistant = MyApplication.getFlightControllerInstance().getFlightAssistant();
        if (flightAssistant == null)
            return;
        flightAssistant.setCollisionAvoidanceEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_collision_avoidance, !isChecked);
                }
            }
        });
        flightAssistant.setActiveObstacleAvoidanceEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_collision_avoidance, !isChecked);
                }
            }
        });
    }

    /**
     * 脚架
     */
    private void setAutomaticMovement(final boolean isChecked) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.getLandingGear().setAutomaticMovementEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_gear, !isChecked);
                }
            }
        });
    }

    /**
     * 脚架模式
     */
    private void setTripodMode(final boolean isChecked) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setTripodModeEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_tripodmode, !isChecked);
                }
            }
        });
    }

    /**
     * MAX距离限制
     */
    private void setMaxRadius(final boolean isChecked) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setMaxFlightRadiusLimitationEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_maxradius, !isChecked);
                }
            }
        });
    }

    /**
     * MAX高度
     */
    private void setMaxHeight(int i) {
        if (i > 500) {
            i = 500;
            et_maxheight.setText(getResources().getString(R.string.num, i));
        }
        if (i < 20) {
            i = 20;
            et_maxheight.setText(getResources().getString(R.string.num, i));
        }
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setMaxFlightHeight(i, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                }
            }
        });
    }

    /**
     * 返航高度
     */
    private void setGoHomeHeight(int i) {
        if (i > 500) {
            i = 500;
            et_gohomeheight.setText(getResources().getString(R.string.num, i));
        }
        if (i < 20) {
            i = 20;
            et_gohomeheight.setText(getResources().getString(R.string.num, i));
        }
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setGoHomeHeightInMeters(i, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                }
            }
        });
    }

    /**
     * 飞行模式是否可变
     */
    private void setFlightModeChangeability(final boolean isChecked) {
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController == null)
            return;
        flightController.setMultipleFlightModeEnabled(isChecked, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.getDescription());
                    OnUIUtils.setCompoundButtonState(cb_flightmode, !isChecked);
                }
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        AirLink airLink;
        FlightController flightController;
        RemoteController remoteController = MyApplication.getRemoteControllerInstance();
        int parentId = parent.getId();
        switch (parentId) {
            case R.id.sp_flightsetting_lose_connect_action:
                flightController = MyApplication.getFlightControllerInstance();
                if (flightController == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                ConnectionFailSafeBehavior behavior;
                switch (position) {
                    case 0:
                        behavior = ConnectionFailSafeBehavior.HOVER;
                        savedLoseCnnPosition = 0;
                        break;
                    case 1:
                        behavior = ConnectionFailSafeBehavior.LANDING;
                        savedLoseCnnPosition = 1;
                        break;
                    case 2:
                        behavior = ConnectionFailSafeBehavior.GO_HOME;
                        savedLoseCnnPosition = 2;
                        break;
                    default:
                        behavior = ConnectionFailSafeBehavior.HOVER;
                        break;
                }
                flightController.setConnectionFailSafeBehavior(behavior,
                        new CommonCallbacks.CompletionCallback() {
                            @Override
                            public void onResult(DJIError djiError) {
                                if (djiError != null) {
                                    sp_lose_cnn_action.setSelection(savedLoseCnnPosition);
                                }
                            }
                        });
                break;

            case R.id.sp_flight_setting_camera_setting_c1:
                if (remoteController == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                if (remoteController.isCustomizableButtonSupported()) {
                    customButtonSelected(position, 0);
                }
                break;
            case R.id.sp_flight_setting_camera_setting_c2:
                if (remoteController == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                if (remoteController.isCustomizableButtonSupported()) {
                    customButtonSelected(position, 1);
                }
                break;

            case R.id.sp_flight_setting_app_output_port:

                if (remoteController == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                switch (app_output_ports[position]) {
                    case "HDMI":
                        getSecondaryVideoOutputFormatForPort(remoteController, SecondaryVideoOutputPort.HDMI);
                        selectedPort = SecondaryVideoOutputPort.HDMI;
                        if (selectedFormate != null) {
                            remoteController.setSecondaryVideoOutputFormatForHDMI(selectedFormate, new CommonCallbacks.CompletionCallback() {
                                @Override
                                public void onResult(DJIError djiError) {
                                    if (djiError != null) {
                                        OnUIUtils.setToast(djiError.toString());
                                    }
                                }
                            });
                        }
                        break;
                    case "SDI":
                        getSecondaryVideoOutputFormatForPort(remoteController, SecondaryVideoOutputPort.SDI);
                        selectedPort = SecondaryVideoOutputPort.SDI;
                        if (selectedFormate != null) {
                            remoteController.setSecondaryVideoOutputFormatForSDI(selectedFormate, new CommonCallbacks.CompletionCallback() {
                                @Override
                                public void onResult(DJIError djiError) {
                                    if (djiError != null) {
                                        OnUIUtils.setToast(djiError.toString());
                                    }
                                }
                            });
                        }
                        break;
                }

                break;

            case R.id.sp_flight_setting_map_choose:

                break;

            case R.id.sp_flight_setting_work_channel:
                LightbridgeFrequencyBand selected;
                airLink = MyApplication.getAirLinkInstance();
                if (airLink == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                if (work_channels == null || work_channels.length == 0)
                    return;
                switch (work_channels[position]) {
                    case "2.4G":
                        selected = LightbridgeFrequencyBand.FREQUENCY_BAND_2_DOT_4_GHZ;
                        break;
                    case "5.7G":
                        selected = LightbridgeFrequencyBand.FREQUENCY_BAND_5_DOT_7_GHZ;
                        break;
                    case "5.8G":
                        selected = LightbridgeFrequencyBand.FREQUENCY_BAND_5_DOT_8_GHZ;
                        break;
                    default:
                        selected = null;
                        break;
                }
                airLink.getLightbridgeLink().setFrequencyBand(selected,
                        new CommonCallbacks.CompletionCallback() {
                            @Override
                            public void onResult(DJIError djiError) {
                                if (djiError != null) {
                                    OnUIUtils.setToast(djiError.toString());
                                }
                            }
                        });
                break;
            case R.id.sp_flight_setting_app_output_mode:
                remoteController = MyApplication.getRemoteControllerInstance();
                if (remoteController == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                SecondaryVideoDisplayMode mode;
                switch (position) {
                    case 0:
                        mode = SecondaryVideoDisplayMode.SOURCE_1_ONLY;
                        break;
                    case 1:
                        mode = SecondaryVideoDisplayMode.SOURCE_2_ONLY;
                        break;
                    case 2:
                        mode = SecondaryVideoDisplayMode.SOURCE_1_MAIN;
                        break;
                    case 3:
                        mode = SecondaryVideoDisplayMode.SOURCE_2_MAIN;
                        break;
                    default:
                        mode = SecondaryVideoDisplayMode.SOURCE_1_ONLY;
                        break;
                }
                remoteController.setSecondaryVideoDisplay(mode, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.toString());
                        }
                    }
                });
                break;
            case R.id.sp_flight_setting_app_output_formate:
                remoteController = MyApplication.getRemoteControllerInstance();
                if (remoteController == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                switch (position) {
                    case 0:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_1080I_60FPS;
                        break;
                    case 1:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_1080P_60FPS;
                        break;
                    case 2:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_1080I_50FPS;
                        break;
                    case 3:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_1080P_50FPS;
                        break;
                    case 4:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_1080P_30FPS;
                        break;
                    case 5:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_1080P_25FPS;
                        break;
                    case 6:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_1080P_24FPS;
                        break;
                    case 7:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_720P_60FPS;
                        break;
                    case 8:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_720P_50FPS;
                        break;
                    case 9:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_720P_30FPS;
                        break;
                    case 10:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_720P_25FPS;
                        break;
                    case 11:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_720P_24FPS;
                        break;
                    default:
                        selectedFormate = SecondaryVideoFormat.RESOLUTION_1080I_60FPS;
                }
                if (selectedPort == SecondaryVideoOutputPort.HDMI)
                    remoteController.setSecondaryVideoOutputFormatForHDMI(selectedFormate, new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.toString());
                            }
                        }
                    });
                else if (selectedPort == SecondaryVideoOutputPort.SDI)
                    remoteController.setSecondaryVideoOutputFormatForSDI(selectedFormate, new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.toString());
                            }
                        }
                    });
                break;
            case R.id.sp_flight_setting_app_output_pip:
                remoteController = MyApplication.getRemoteControllerInstance();
                if (remoteController == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                PIPPosition pipPosition;
                switch (position) {
                    case 0:
                        pipPosition = PIPPosition.TOP_LEFT;
                        break;
                    case 1:
                        pipPosition = PIPPosition.TOP_RIGHT;
                        break;
                    case 2:
                        pipPosition = PIPPosition.BOTTOM_LEFT;
                        break;
                    case 3:
                        pipPosition = PIPPosition.BOTTOM_RIGHT;
                        break;
                    default:
                        pipPosition = PIPPosition.TOP_LEFT;
                }
                remoteController.setSecondaryVideoPIPPosition(pipPosition, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.toString());
                        }
                    }
                });
                break;
            case R.id.sp_flight_setting_tap_zoom:
                Aircraft aircraft = (Aircraft) MyApplication.getProductInstance();
                if (aircraft == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                List<Camera> cameras = aircraft.getCameras();
                if (cameras != null && cameras.size() > 0) {
                    switch (position) {
                        case 0:
                            setCamerasTapZoom(cameras, 1);
                            break;
                        case 1:
                            setCamerasTapZoom(cameras, 2);
                            break;
                        case 2:
                            setCamerasTapZoom(cameras, 3);
                            break;
                        case 3:
                            setCamerasTapZoom(cameras, 4);
                            break;
                        case 4:
                            setCamerasTapZoom(cameras, 5);
                            break;
                    }
                }
                break;
            case R.id.sp_flight_setting_main_control:
                remoteController = MyApplication.getRemoteControllerInstance();
                if (remoteController == null) {
                    if (finishListener != null)
                        finishListener.onFinish();
                    return;
                }
                RCMode rcMode = RCMode.MASTER;
                switch (position) {
                    case 1:
                        rcMode = RCMode.SLAVE;
                        break;
                    case 2:
                        rcMode = RCMode.NORMAL;
                        break;
                }
                remoteController.setMode(rcMode, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        OnUIUtils.setToast(djiError.toString());
                    }
                });
                break;
            case R.id.sp_flight_setting_main_camera:
                String cameraName = this.cameras.get(position).getDisplayName();
                if (cameraName.contains("payload") || cameraName.contains("PayLoad")
                        || cameraName.contains("Payload")) {
                    mActivity.showRedPlus();
                } else {
                    mActivity.hideRedPlus();
                }
                switch (position) {
                    case 0:
                        main_camera_setting = PhysicalSource.LEFT_CAM.value();
                        if (main_camera_setting == assistant_camera_setting) {
                            assistant_camera_setting++;

                        }
                        break;
                    case 1:
                        main_camera_setting = PhysicalSource.RIGHT_CAM.value();
                        break;
                }

                break;
            case R.id.sp_flight_setting_assistant_camera:
                switch (position) {
                    case 0:
                        assistant_camera_setting = PhysicalSource.LEFT_CAM.value();
                        break;
                    case 1:
                        assistant_camera_setting = PhysicalSource.RIGHT_CAM.value();
                        break;
                    case 2:
                        assistant_camera_setting = PhysicalSource.FPV_CAM.value();
                        break;
                }

                break;
            case R.id.sp_flightsetting_alarm_limit:

                break;
            case R.id.sp_flightsetting_measure_unit:

                break;
            case R.id.sp_flightsetting_cloud_data:
                break;
        }
        if (finishListener != null)
            finishListener.onFinish();
    }

    private void setCamerasTapZoom(List<Camera> cameras, int zoom) {
        for (int i = 0; i < cameras.size(); i++) {
            cameras.get(i).setTapZoomMultiplier(zoom, new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError djiError) {
                    if (djiError != null)
                        OnUIUtils.setToast(djiError.toString());
                }
            });
        }
    }

    private void customButtonSelected(int position, int index) {
        RemoteController controller = MyApplication.getRemoteControllerInstance();
        CommonCallbacks.CompletionCallback completionCallback = new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError != null) {
                    OnUIUtils.setToast(djiError.toString());
                } else {
                    OnUIUtils.setToast("设置成功");
                }
            }
        };
        if (controller == null) {
            return;
        }
        switch (position) {
            case 0://机头指示灯
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.Spotlight, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.Spotlight, completionCallback);
                }
                break;
            case 1://中央测光
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.CenterMetering, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.CenterMetering, completionCallback);
                }
                break;
            case 2://ae解锁
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.AeLock, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.AeLock, completionCallback);
                }
                break;
            case 3://相机
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.CameraSetting, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.CameraSetting, completionCallback);
                }
                break;
            case 4://回中/朝下  GimbalPitchYawCenter不确定
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.GimbalPitchYawCenter, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.GimbalPitchYawCenter, completionCallback);
                }
                break;
            case 5://FVP模式/跟随模式 SwitchGimbalFpv不确定SwitchGimbalFpv
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.SwitchGimbalFpv, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.SwitchGimbalFpv, completionCallback);
                }
                break;
            case 6://地图/FPV切换  MapSwitch不确定
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.MapSwitch, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.MapSwitch, completionCallback);
                }
                break;
            case 7://电池页面Battery
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.Battery, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.Battery, completionCallback);
                }
                break;
            case 8://回放PlayBack
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.PlayBack, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.PlayBack, completionCallback);
                }
                break;
            case 9://中心对焦CenterFocus
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.CenterFocus, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.CenterFocus, completionCallback);
                }
                break;
            case 10://未定义NOT_DEFINED
                if (index == 0) {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C1, ProfessionalRC.ButtonAction.NOT_DEFINED, completionCallback);
                } else {
                    controller.customizeButton(ProfessionalRC.CustomizableButton.C2, ProfessionalRC.ButtonAction.NOT_DEFINED, completionCallback);
                }
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        if (finishListener != null)
            finishListener.onFinish();
    }

    private void getSecondaryVideoOutputFormatForPort(RemoteController remoteController, SecondaryVideoOutputPort port) {
        if (SecondaryVideoOutputPort.HDMI == port) {
            remoteController.getSecondaryVideoOutputFormatForHDMI(new CommonCallbacks.CompletionCallbackWith<SecondaryVideoFormat>() {
                @Override
                public void onSuccess(SecondaryVideoFormat secondaryVideoFormat) {
                    if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080I_60FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 0);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080I_50FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 1);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_60FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 2);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_50FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 3);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_30FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 4);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_25FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 5);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_24FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 6);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_60FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 7);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_50FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 8);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_30FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 9);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_25FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 10);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_24FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 11);
                    }
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null)
                        OnUIUtils.setToast(djiError.toString());
                }
            });
        } else if (SecondaryVideoOutputPort.SDI == port) {
            remoteController.getSecondaryVideoOutputFormatForSDI(new CommonCallbacks.CompletionCallbackWith<SecondaryVideoFormat>() {
                @Override
                public void onSuccess(SecondaryVideoFormat secondaryVideoFormat) {
                    if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080I_60FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 0);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080I_50FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 1);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_60FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 2);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_50FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 3);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_30FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 4);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_25FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 5);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_1080P_24FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 6);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_60FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 7);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_50FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 8);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_30FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 9);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_25FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 10);
                    } else if (secondaryVideoFormat == SecondaryVideoFormat.RESOLUTION_720P_24FPS) {
                        OnUIUtils.setSpinnerSelection(sp_out_put_formate, 11);
                    }
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null)
                        OnUIUtils.setToast(djiError.toString());
                }
            });
        }
    }

    private void setChannelSpinner() {
        sp_work_channel = view.findViewById(R.id.sp_flight_setting_work_channel);
        ArrayAdapter channelAdapter = new ArrayAdapter(context, R.layout.textview_item_flight_menu, work_channels);
        channelAdapter.setDropDownViewResource(R.layout.textview_item_flight_menu);
        sp_work_channel.setAdapter(channelAdapter);
        sp_work_channel.setOnItemSelectedListener(this);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    private void initBySDK() {
        Log.e(" initBySDK", "-----------");
        /**
         * flightController
         */
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController != null) {

            //飞行模式是否可变
            flightController.getMultipleFlightModeEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                @Override
                public void onSuccess(Boolean aBoolean) {
                    OnUIUtils.setCompoundButtonState(cb_flightmode, aBoolean);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setCompoundButtonState(cb_flightmode, false);
                    }
                }
            });

            //返航高度
            flightController.getGoHomeHeightInMeters(new CommonCallbacks.CompletionCallbackWith<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    OnUIUtils.setEditViewText(et_gohomeheight, integer + "");
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setEditViewText(et_gohomeheight, "350");
                    }
                }
            });

            //MAX高度
            flightController.getMaxFlightHeight(new CommonCallbacks.CompletionCallbackWith<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    OnUIUtils.setEditViewText(et_maxheight, integer + "");
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setEditViewText(et_maxheight, "500");
                    }
                }
            });

            //MAX距离限制
            flightController.getMaxFlightRadiusLimitationEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                @Override
                public void onSuccess(Boolean aBoolean) {
                    OnUIUtils.setCompoundButtonState(cb_maxradius, aBoolean);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setCompoundButtonState(cb_maxradius, false);
                    }
                }
            });

            //脚架模式
            flightController.getTripodModeEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                @Override
                public void onSuccess(Boolean aBoolean) {
                    OnUIUtils.setCompoundButtonState(cb_tripodmode, aBoolean);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setCompoundButtonState(cb_tripodmode, false);
                    }
                }
            });
            //脚架
            boolean isLandingGearMovable = flightController.isLandingGearMovable();
            if (isLandingGearMovable) {
                LandingGear landingGear = flightController.getLandingGear();
                landingGear.getAutomaticMovementEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        OnUIUtils.setCompoundButtonState(cb_gear, aBoolean);
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setCompoundButtonState(cb_gear, false);
                        }
                    }
                });

                if (flightController != null) {
                    //FlightController回调
                    flightController.setStateCallback(new FlightControllerState.Callback() {
                        @Override
                        public void onUpdate(@NonNull FlightControllerState flightControllerState) {
                            //飞行时间
                            setFlightTime(flightControllerState.getFlightTimeInSeconds() + "");
                        }
                    });
                }
            }


            boolean isFlightAssistantSupported = flightController.isFlightAssistantSupported();
            if (isFlightAssistantSupported) {
                final FlightAssistant flightAssistant = flightController.getFlightAssistant();
                //视觉避障系统
                if (flightAssistant != null) {
                    flightAssistant.getCollisionAvoidanceEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                        @Override
                        public void onSuccess(Boolean aBoolean) {
                            OnUIUtils.setCompoundButtonState(cb_collision_avoidance, aBoolean);
                            if (aBoolean) {
                                cb_rth_avoidance.setChecked(true);
                                setRTHObstacleAvoidance(true);
                            } else {
                                //返航障碍物检测
                                flightAssistant.getRTHObstacleAvoidanceEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                                    @Override
                                    public void onSuccess(Boolean aBoolean) {
                                        OnUIUtils.setCompoundButtonState(cb_rth_avoidance, aBoolean);
                                    }

                                    @Override
                                    public void onFailure(DJIError djiError) {
                                        if (djiError != null) {
                                            OnUIUtils.setToast(djiError.getDescription());
                                            OnUIUtils.setCompoundButtonState(cb_rth_avoidance, false);
                                        }
                                    }
                                });
                            }
                        }

                        @Override
                        public void onFailure(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.getDescription());
                                OnUIUtils.setCompoundButtonState(cb_collision_avoidance, false);
                            }
                        }
                    });
                    //着陆保护
                    flightAssistant.getLandingProtectionEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                        @Override
                        public void onSuccess(Boolean aBoolean) {
                            OnUIUtils.setCompoundButtonState(cb_landing_protection, aBoolean);
                        }

                        @Override
                        public void onFailure(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.getDescription());
                                OnUIUtils.setCompoundButtonState(cb_landing_protection, false);
                            }
                        }
                    });
                }
            }

            //失控行为
            flightController.getConnectionFailSafeBehavior(new CommonCallbacks.CompletionCallbackWith<ConnectionFailSafeBehavior>() {
                @Override
                public void onSuccess(ConnectionFailSafeBehavior connectionFailSafeBehavior) {
                    if (connectionFailSafeBehavior.equals(ConnectionFailSafeBehavior.HOVER)) {
                        OnUIUtils.setSpinnerSelection(sp_lose_cnn_action, 0);
                        savedLoseCnnPosition = 0;
                    } else if (connectionFailSafeBehavior.equals(ConnectionFailSafeBehavior.LANDING)) {
                        OnUIUtils.setSpinnerSelection(sp_lose_cnn_action, 1);
                        savedLoseCnnPosition = 1;
                    } else if (connectionFailSafeBehavior.equals(ConnectionFailSafeBehavior.GO_HOME)) {
                        OnUIUtils.setSpinnerSelection(sp_lose_cnn_action, 2);
                        savedLoseCnnPosition = 2;
                    } else {
                        OnUIUtils.setSpinnerSelection(sp_lose_cnn_action, 0);
                        savedLoseCnnPosition = 0;
                    }
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setSpinnerSelection(sp_lose_cnn_action, 0);
                    }
                }
            });

            //智能低电量返航
            flightController.getSmartReturnToHomeEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                @Override
                public void onSuccess(Boolean aBoolean) {
                    OnUIUtils.setCompoundButtonState(cb_smart_rth, aBoolean);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setCompoundButtonState(cb_smart_rth, false);
                    }
                }
            });

            //严重低电量报警
            flightController.getSeriousLowBatteryWarningThreshold(new CommonCallbacks.CompletionCallbackWith<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    OnUIUtils.setSeekbarProgress(sb_serious_lowbattery_warning, integer - 10);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setSeekbarProgress(sb_serious_lowbattery_warning, 35);
                    }
                }
            });

            //低电量报警
            flightController.getLowBatteryWarningThreshold(new CommonCallbacks.CompletionCallbackWith<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    OnUIUtils.setSeekbarProgress(sb_lowbattery_warning, integer - 15);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setSeekbarProgress(sb_lowbattery_warning, 35);
                    }
                }
            });

            //IMU
            flightController.setIMUStateCallback(this);

            //指南针
            final Compass compass = flightController.getCompass();
            compass.setCompassStateCallback(this);

            //鸣叫
            flightController.getESCBeepEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                @Override
                public void onSuccess(Boolean aBoolean) {
                    OnUIUtils.setCompoundButtonState(cb_beeping, aBoolean);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    if (djiError != null) {
                        OnUIUtils.setToast(djiError.getDescription());
                        OnUIUtils.setCompoundButtonState(cb_beeping, false);
                    }
                }
            });
        }

        /**
         * remoteController
         */
        RemoteController remoteController = MyApplication.getRemoteControllerInstance();
        if (remoteController != null) {
            //遥控器名称和序列号
            remoteController.getConnectedMasterCredentials(new CommonCallbacks.CompletionCallbackWith<Credentials>() {
                @Override
                public void onSuccess(Credentials credentials) {
                    TextView textViewName = view.findViewById(R.id.tv_flightsetting_remote_name);
                    OnUIUtils.setTextView(textViewName, credentials.getName());

                    TextView textViewId = view.findViewById(R.id.tv_flightsetting_remote_id);
                    OnUIUtils.setTextView(textViewId, String.valueOf(credentials.getID()));
                }

                @Override
                public void onFailure(DJIError djiError) {

                }
            });

            //主辅控
            if (masterSlaveAdapter != null) {
                remoteController.getMode(new CommonCallbacks.CompletionCallbackWith<RCMode>() {
                    @Override
                    public void onSuccess(RCMode rcMode) {
                        if (rcMode == RCMode.SLAVE) {
                            sp_master_slave.setSelection(1);
                        } else {
                            sp_master_slave.setSelection(0);
                        }
                    }

                    @Override
                    public void onFailure(DJIError djiError) {

                    }
                });
            }

            //视频输出模式
            remoteController.getSecondaryVideoDisplay(new CommonCallbacks.CompletionCallbackWith<SecondaryVideoDisplayMode>() {
                @Override
                public void onSuccess(SecondaryVideoDisplayMode lightbridgeSecondaryVideoDisplayMode) {
                    if (displayModeAdapter != null) {
                        if (lightbridgeSecondaryVideoDisplayMode == SecondaryVideoDisplayMode.SOURCE_1_ONLY) {
                            sp_out_put_mode.setSelection(0);
                        } else if (lightbridgeSecondaryVideoDisplayMode == SecondaryVideoDisplayMode.SOURCE_2_ONLY) {
                            sp_out_put_mode.setSelection(1);
                        } else if (lightbridgeSecondaryVideoDisplayMode == SecondaryVideoDisplayMode.SOURCE_1_MAIN) {
                            sp_out_put_mode.setSelection(2);
                        } else if (lightbridgeSecondaryVideoDisplayMode == SecondaryVideoDisplayMode.SOURCE_2_MAIN) {
                            sp_out_put_mode.setSelection(3);
                        }
                    }
                }

                @Override
                public void onFailure(DJIError djiError) {
                    OnUIUtils.setToast(djiError.toString());
                }
            });


            //画中画
            remoteController.getSecondaryVideoPIPPosition(new CommonCallbacks.CompletionCallbackWith<PIPPosition>() {
                @Override
                public void onSuccess(PIPPosition lightbridgePIPPosition) {
                    if (pipAdapter != null) {
                        if (lightbridgePIPPosition == PIPPosition.TOP_LEFT) {
                            sp_pip.setSelection(0);
                        } else if (lightbridgePIPPosition == PIPPosition.TOP_RIGHT) {
                            sp_pip.setSelection(1);
                        } else if (lightbridgePIPPosition == PIPPosition.BOTTOM_LEFT) {
                            sp_pip.setSelection(2);
                        } else if (lightbridgePIPPosition == PIPPosition.BOTTOM_RIGHT) {
                            sp_pip.setSelection(3);
                        }
                    }
                }

                @Override
                public void onFailure(DJIError djiError) {
                    OnUIUtils.setToast(djiError.toString());
                }
            });
        }

        /**
         * airLink
         */
        AirLink airLink = MyApplication.getAirLinkInstance();
        if (airLink != null) {
            boolean isLightbridgeLinkSupported = airLink.isLightbridgeLinkSupported();
            if (isLightbridgeLinkSupported) {
                final LightbridgeLink lightbridgeLink = airLink.getLightbridgeLink();
                //工作频段
                lightbridgeLink.getSupportedFrequencyBands(new CommonCallbacks.CompletionCallbackWith<LightbridgeFrequencyBand[]>() {
                    @Override
                    public void onSuccess(LightbridgeFrequencyBand[] lightbridgeFrequencyBands) {
                        if (lightbridgeFrequencyBands != null) {
                            int size = lightbridgeFrequencyBands.length;
                            work_channels = new String[size];
                            for (int i = 0; i < size; i++) {
                                if (lightbridgeFrequencyBands[i] == LightbridgeFrequencyBand.FREQUENCY_BAND_2_DOT_4_GHZ) {
                                    work_channels[i] = "2.4G";
                                } else if (lightbridgeFrequencyBands[i] == LightbridgeFrequencyBand.FREQUENCY_BAND_5_DOT_7_GHZ) {
                                    work_channels[i] = "5.7G";
                                } else if (lightbridgeFrequencyBands[i] == LightbridgeFrequencyBand.FREQUENCY_BAND_5_DOT_8_GHZ) {
                                    work_channels[i] = "5.8G";
                                }
                            }
                            setChannelSpinner();
                            lightbridgeLink.getFrequencyBand(new CommonCallbacks.CompletionCallbackWith<LightbridgeFrequencyBand>() {
                                @Override
                                public void onSuccess(LightbridgeFrequencyBand lightbridgeFrequencyBand) {
                                    if (lightbridgeFrequencyBand == LightbridgeFrequencyBand.FREQUENCY_BAND_2_DOT_4_GHZ) {
                                        int position = getStringArrayIndex(work_channels, "2.4G");
                                        sp_work_channel.setSelection(position);
                                        savedFrequencePosition = position;
                                    } else if (lightbridgeFrequencyBand == LightbridgeFrequencyBand.FREQUENCY_BAND_5_DOT_7_GHZ) {
                                        int position = getStringArrayIndex(work_channels, "5.7G");
                                        sp_work_channel.setSelection(position);
                                        savedFrequencePosition = position;
                                    } else if (lightbridgeFrequencyBand == LightbridgeFrequencyBand.FREQUENCY_BAND_5_DOT_8_GHZ) {
                                        int position = getStringArrayIndex(work_channels, "5.8G");
                                        sp_work_channel.setSelection(position);
                                        savedFrequencePosition = position;
                                    }
                                }

                                @Override
                                public void onFailure(DJIError djiError) {
                                    OnUIUtils.setToast(djiError.getDescription());
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        OnUIUtils.setToast(djiError.getDescription());
                        work_channels = new String[0];
                    }
                });

                //app输出模式
//            lightbridgeLink.getSecondaryVideoOutputFormatForPort();
                //信道模式
                lightbridgeLink.getChannelSelectionMode(new CommonCallbacks.CompletionCallbackWith<ChannelSelectionMode>() {
                    @Override
                    public void onSuccess(ChannelSelectionMode channelSelectionMode) {
                        if (channelSelectionMode.value() == ChannelSelectionMode.MANUAL.value()) {
                            OnUIUtils.setCompoundButtonState(rb_manual, true);
                        } else
                            OnUIUtils.setCompoundButtonState(rb_automatic, true);
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setCompoundButtonState(rb_automatic, true);
                        }
                    }
                });

                //EXT端口
                lightbridgeLink.getEXTVideoInputPortEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        OnUIUtils.setCompoundButtonState(cb_ext_port, aBoolean);
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setCompoundButtonState(cb_ext_port, false);
                        }
                    }
                });

                //带宽分配
                if (lightbridgeLink.isDualEncodeModeSupported()) {
                    view.findViewById(R.id.flightsetting_tv_bandwidth_issupport).setVisibility(GONE);
                    lightbridgeLink.getBandwidthAllocationForHDMIVideoInputPort(new CommonCallbacks.CompletionCallbackWith<Float>() {
                        @Override
                        public void onSuccess(Float aFloat) {
                            OnUIUtils.setSeekbarProgress(sb_bandwidth, aFloat.intValue());
                        }

                        @Override
                        public void onFailure(DJIError djiError) {
                            if (djiError != null) {
                                OnUIUtils.setToast(djiError.getDescription());
                                OnUIUtils.setSeekbarProgress(sb_bandwidth, 0);
                            }
                        }
                    });
                }
            }
            //下行带宽
            WiFiLink wiFiLink = airLink.getWiFiLink();
            if (wiFiLink != null) {
                wiFiLink.getDataRate(new CommonCallbacks.CompletionCallbackWith<WifiDataRate>() {
                    @Override
                    public void onSuccess(WifiDataRate wifiDataRate) {
                        TextView tv = view.findViewById(R.id.tv_flight_setting_download_rate);
                        if (wifiDataRate == WifiDataRate.RATE_1_MBPS) {
                            tv.setText("1Mbps");
                        } else if (wifiDataRate == WifiDataRate.RATE_2_MBPS) {
                            tv.setText("2Mbps");
                        } else if (wifiDataRate == WifiDataRate.RATE_4_MBPS) {
                            tv.setText("4Mbps");
                        } else {
                            tv.setText(wifiDataRate.value());
                        }

                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        OnUIUtils.setToast(djiError.toString());
                    }
                });
            }
            //飞控序列号
            airLink.getSerialNumber(new CommonCallbacks.CompletionCallbackWith<String>() {
                @Override
                public void onSuccess(String s) {
                    TextView tv = view.findViewById(R.id.tv_flightsetting_air_link_sn);
                    OnUIUtils.setTextView(tv, s);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    OnUIUtils.setToast(djiError.toString());
                }
            });
            //图传相机设置
            if (airLink.isOcuSyncLinkSupported()) {
                LinearLayout ll_camera_select_btn = findViewById(R.id.flightsetting_ll_camera_select);
                ll_camera_select_btn.setVisibility(VISIBLE);
                ll_camera_select_btn.setOnClickListener(this);
            }
        }


        /**
         * batteryInstance
         */
        List<Battery> batteries = MyApplication.getBatteryInstance();
        Log.e("batteries", "init");
        batteryItems = new ArrayList<>();
//        batteryInfoAdapter = new BatteryInfoAdapter(batteryItems, context);
//        lv_battery_info.setAdapter(batteryInfoAdapter);
//        setListViewHeightBasedOnChildren(lv_battery_info);
        if (batteries != null && batteries.size() > 0) {
            fullBatteries = new int[batteries.size()];
            remainBatteris = new int[batteries.size()];
            //battery回调
            for (int i = 0; i < batteries.size(); i++) {
                final int finalI = i;
                BatteryItem item = new BatteryItem();
                batteryItems.add(item);
                batteries.get(i).setStateCallback(new BatteryState.Callback() {
                    @Override
                    public void onUpdate(BatteryState batteryState) {
                        //总电量
                        int capacity = batteryState.getFullChargeCapacity();
                        Log.e("batteries i=" + finalI, "capacity=" + capacity);
                        fullBatteries[finalI] = capacity;
                        remainBatteris[finalI] = batteryState.getChargeRemaining();
                        int sum = 0;
                        int remain = 0;
                        for (int j = 0; j < fullBatteries.length; j++) {
                            sum += fullBatteries[j];
                            remain += remainBatteris[j];
                        }
                        NumberFormat numberFormat = NumberFormat.getInstance();
                        numberFormat.setMaximumFractionDigits(2);
                        String result = numberFormat.format((float) remain / (float) sum * 100);
                        OnUIUtils.setTextView(((TextView) view.findViewById(R.id.flightsetting_tv_fullbattery)),
                                result + "%");
                        String remainTime = numberFormat.format((float) 38 * (float) remain / (float) sum);
                        OnUIUtils.setTextView((TextView) view.findViewById(R.id.flightsetting_tv_flighttime), remainTime + "min");
                        //
                        batteryItems.get(finalI).setState(batteryState);
//                        batteryInfoAdapter.notifyDataSetChanged();
//                        setListViewHeightBasedOnChildren(lv_battery_info);
                    }
                });
                batteries.get(i).getCellVoltages(new CommonCallbacks.CompletionCallbackWith<Integer[]>() {
                    @Override
                    public void onSuccess(Integer[] integers) {
                        batteryItems.get(finalI).setCellVoltages(integers);
//                        batteryInfoAdapter.notifyDataSetChanged();
//                        setListViewHeightBasedOnChildren(lv_battery_info);
                    }

                    @Override
                    public void onFailure(DJIError djiError) {

                    }
                });
            }


        } else {
            lv_battery_info.setVisibility(View.GONE);
        }

        /**
         *  gimbal
         */
        List<Gimbal> gimbalList = MyApplication.getGimbalInstance();
        if (gimbalList != null && gimbalList.size() > 0) {
            for (int i = 0; i < gimbalList.size(); i++) {
                Gimbal gimbal = gimbalList.get(i);
                if (gimbal == null)
                    return;
                gimbal.getPitchRangeExtensionEnabled(new CommonCallbacks.CompletionCallbackWith<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        OnUIUtils.setCompoundButtonState(cb_gimbal_limit, aBoolean);
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.getDescription());
                            OnUIUtils.setCompoundButtonState(cb_gimbal_limit, false);
                        }
                    }
                });
            }
        }

        //飞控参数设置
        //app版本
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_ACTIVITIES);
            String versionName = packageInfo.versionName;
            TextView appVersion = view.findViewById(R.id.tv_flightsetting_app_version);
            appVersion.setText(versionName);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //飞机型号
        BaseProduct baseProduct = MyApplication.getProductInstance();
        if (baseProduct != null) {
            String name = baseProduct.getModel().getDisplayName();
            TextView tv = view.findViewById(R.id.tv_flightsetting_aircraft_name);
            tv.setText(name);

            //云台
            Aircraft aircraft = (Aircraft) baseProduct;
            List<Gimbal> list = aircraft.getGimbals();
            if (list == null || list.size() <= 0)
                return;
            gimbalBuilder = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                list.get(i).getSerialNumber(new CommonCallbacks.CompletionCallbackWith<String>() {
                    @Override
                    public void onSuccess(String s) {
                        if (gimbalBuilder.length() == 0) {
                            gimbalBuilder.append(s);
                        } else {
                            gimbalBuilder.append("/" + s);
                        }
                        OnUIUtils.setTextView(tv_gimbal_no, gimbalBuilder.toString());
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        OnUIUtils.setToast(djiError.toString());
                    }
                });
            }
            //相机单次放缩比例
            Camera cameras = aircraft.getCamera();
            if (cameras != null) {
                cameras.getTapZoomMultiplier(new CommonCallbacks.CompletionCallbackWith<Integer>() {
                    @Override
                    public void onSuccess(Integer integer) {
                        switch (integer) {
                            case 1:
                                sp_tap_zoom.setSelection(0);
                                break;
                            case 2:
                                sp_tap_zoom.setSelection(1);
                                break;
                            case 3:
                                sp_tap_zoom.setSelection(2);
                                break;
                            case 4:
                                sp_tap_zoom.setSelection(3);
                                break;
                            case 5:
                                sp_tap_zoom.setSelection(4);
                                break;
                        }
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        OnUIUtils.setToast(djiError.toString());
                    }
                });
            }

        }
    }

    //图传相机设置
    private void setPhysicalSourse(int primary, int sec) {
        AirLink airLink = MyApplication.getAirLinkInstance();
        if (airLink == null)
            return;

        OcuSyncLink ocuSyncLink = airLink.getOcuSyncLink();

        PhysicalSource main;
        PhysicalSource secondary;
//        PhysicalSource main = PhysicalSource.find(primary == 0 ? 6 : 7);
//        PhysicalSource secondary = PhysicalSource.find(sec == 0 ? 6 : sec == 1 ? 7 : 5);
        switch (primary){
            case 6:
                main = PhysicalSource.LEFT_CAM;
                break;
            case 7:
                main = PhysicalSource.RIGHT_CAM;
                break;
                default:
                    main = PhysicalSource.EXT;
        }
        switch (sec){
            case 5:
                secondary = PhysicalSource.FPV_CAM;
                break;
            case 6:
                secondary = PhysicalSource.LEFT_CAM;
                break;
            case 7:
                secondary = PhysicalSource.RIGHT_CAM;
                break;
                default:
                    secondary = PhysicalSource.EXT;
        }

        ocuSyncLink.assignSourceToPrimaryChannel(main, secondary,
                new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast(djiError.toString());
                            Log.e("info", "main = " + main_camera_setting + ",assis = " + assistant_camera_setting);
                        }
                    }
                });
    }

    /**
     * 设置listview高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * IMU回调
     */
    @Override
    public void onUpdate(@NonNull IMUState imuState) {
        if (findViewById(R.id.flightsetting_ll_2_sensor_mode).getVisibility() != VISIBLE
                || !rb_imu.isChecked())
            return;

        OnUIUtils.setTextView((TextView) findViewById(R.id.flightsetting_tv_acc_state),
                getSensorState(imuState.getAccelerometerState()));
        OnUIUtils.setTextView((TextView) findViewById(R.id.flightsetting_tv_gyro_state),
                getSensorState(imuState.getGyroscopeState()));

        float accelerometerValue = imuState.getAccelerometerValue();
        float gyroscopeValue = imuState.getGyroscopeValue();
        int index = imuState.getIndex();
        if (index == 0) {
            if (fl_imu_index_1.getVisibility() == INVISIBLE) {
                OnUIUtils.setViewVisibility(fl_imu_index_2, View.INVISIBLE);
                OnUIUtils.setViewVisibility(fl_imu_index_1, View.VISIBLE);
            }
            OnUIUtils.setTextView((TextView) findViewById(R.id.flightsetting_tv_acc1),
                    getResources().getString(R.string.flightsetting_acc1, accelerometerValue));
            OnUIUtils.setProgressBarProgress((ProgressBar) findViewById(R.id.flightsetting_pb_acc1),
                    (int) accelerometerValue * 100);
            OnUIUtils.setTextView((TextView) findViewById(R.id.flightsetting_tv_gyro1),
                    getResources().getString(R.string.flightsetting_gyro1, gyroscopeValue));
            OnUIUtils.setProgressBarProgress((ProgressBar) findViewById(R.id.flightsetting_pb_gyro1),
                    (int) gyroscopeValue * 100);
        } else if (index == 1) {
            if (fl_imu_index_2.getVisibility() == INVISIBLE) {
                OnUIUtils.setViewVisibility(fl_imu_index_1, View.INVISIBLE);
                OnUIUtils.setViewVisibility(fl_imu_index_2, View.VISIBLE);
            }
            OnUIUtils.setTextView((TextView) findViewById(R.id.flightsetting_tv_acc2),
                    getResources().getString(R.string.flightsetting_acc2, accelerometerValue));
            OnUIUtils.setProgressBarProgress((ProgressBar) findViewById(R.id.flightsetting_pb_acc2),
                    (int) accelerometerValue * 100);
            OnUIUtils.setTextView((TextView) findViewById(R.id.flightsetting_tv_gyro2),
                    getResources().getString(R.string.flightsetting_gyro2, gyroscopeValue));
            OnUIUtils.setProgressBarProgress((ProgressBar) findViewById(R.id.flightsetting_pb_gyro2),
                    (int) gyroscopeValue * 100);
        }
    }

    /**
     * 指南针回调
     */
    @Override
    public void onUpdate(@NonNull CompassState compassState) {
        if (findViewById(R.id.flightsetting_ll_2_sensor_mode).getVisibility() != VISIBLE
                || !rb_compass.isChecked())
            return;

        int sensorValue = compassState.getSensorValue();
        int index = compassState.getIndex();
        if (index == 0) {
            if (fl_compass_index_1.getVisibility() == INVISIBLE) {
                OnUIUtils.setViewVisibility(fl_compass_index_2, View.INVISIBLE);
                OnUIUtils.setViewVisibility(fl_compass_index_1, View.VISIBLE);
            }
            OnUIUtils.setTextView((TextView) findViewById(R.id.flightsetting_tv_compass1),
                    getResources().getString(R.string.flightsetting_compass1, sensorValue));
            OnUIUtils.setProgressBarProgress((ProgressBar) findViewById(R.id.flightsetting_pb_compass1),
                    sensorValue);
        } else if (index == 1) {
            if (fl_compass_index_2.getVisibility() == INVISIBLE) {
                OnUIUtils.setViewVisibility(fl_compass_index_1, View.INVISIBLE);
                OnUIUtils.setViewVisibility(fl_compass_index_2, View.VISIBLE);
            }
            OnUIUtils.setTextView((TextView) findViewById(R.id.flightsetting_tv_compass2),
                    getResources().getString(R.string.flightsetting_compass1, sensorValue));
            OnUIUtils.setProgressBarProgress((ProgressBar) findViewById(R.id.flightsetting_pb_compass2),
                    sensorValue);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        //清除回调
        try {
            FlightController flightController = MyApplication.getFlightControllerInstance();
            if (flightController != null) {
//                flightController.setStateCallback(null);
                flightController.setIMUStateCallback(null);
                flightController.getCompass().setCompassStateCallback(null);
            }
            AirLink airLink = MyApplication.getAirLinkInstance();
            if (airLink != null) {
//                airLink.setCountryCodeCallback(null);
//                airLink.setDownlinkSignalQualityCallback(null);
//                airLink.setUplinkSignalQualityCallback(null);
            }
            RemoteController remoteController = MyApplication.getRemoteControllerInstance();
            if (remoteController != null) {
//                remoteController.setChargeRemainingCallback(null);
//                remoteController.setGPSDataCallback(null);
//                remoteController.setHardwareStateCallback(null);
//                remoteController.setFocusControllerStateCallback(null);
//                remoteController.setMasterSlaveStateCallback(null);
//                remoteController.setProRCEventCallback(null);
//                remoteController.setGimbalControlRequestFromSlaveCallback(null);
            }
            List<Battery> batteries = MyApplication.getBatteryInstance();
            if (batteries != null) {
                for (int i = 0; i < batteries.size(); i++) {
                    batteries.get(i).setStateCallback(null);
                }
            }
        } catch (Exception ignored) {

        }
    }

    /**
     * 电池详情Adapter
     */
    class BatteryAdapter extends RecyclerView.Adapter<BatteryAdapter.BatteryHolder> {

        private List<String[]> batteryList;

        BatteryAdapter() {
            batteryList = new ArrayList<>();
        }

        public BatteryAdapter(List<String[]> batteryList) {
            this.batteryList = batteryList;
        }

        @Override
        public BatteryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new BatteryHolder(LayoutInflater.from(context).inflate(R.layout.item_battery_info, parent,
                    false));
        }

        @Override
        public void onBindViewHolder(BatteryHolder holder, int position) {
            holder.sn.setText(batteryList.get(position)[0]);
            holder.state.setText(batteryList.get(position)[1]);
            holder.date.setText(batteryList.get(position)[2]);
            holder.count.setText(batteryList.get(position)[3]);
        }

        @Override
        public int getItemCount() {
            return batteryList.size();
        }

        class BatteryHolder extends RecyclerView.ViewHolder {

            TextView sn, state, date, count;

            private BatteryHolder(View view) {
                super(view);
                sn = (TextView) view.findViewById(R.id.battery_tv_sn);
                state = (TextView) view.findViewById(R.id.battery_tv_state);
                date = (TextView) view.findViewById(R.id.battery_tv_date);
                count = (TextView) view.findViewById(R.id.battery_tv_count);
            }
        }
    }

    //设置飞行时间
    public void setFlightTime(String s) {
        OnUIUtils.setTextView(((TextView) view.findViewById(R.id.flightsetting_tv_flighttime)), s);
    }

    //是否显示航迹
    public void setTrackVisible(boolean b) {
        cb_track.setChecked(b);
    }
}
